Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
93bc3fb7e9 | ||
|
|
622b6cbc9f | ||
|
|
c6e49fdb47 | ||
|
|
1648698e18 | ||
|
|
24a2fe26ca | ||
|
|
445e78fb36 | ||
|
|
7e8556e425 | ||
|
|
1ca34f2fc3 | ||
|
|
fd8f5c6742 | ||
|
|
3bc000618f | ||
|
|
bcde98d837 | ||
|
|
b956538599 | ||
|
|
b9362bdb0d | ||
|
|
f0c9663399 | ||
|
|
b2e9058646 | ||
|
|
d680f1136d | ||
|
|
1e8c21c099 | ||
|
|
9b50aa624e | ||
|
|
3f6f85d3d5 | ||
|
|
4c0acdd16d | ||
|
|
ddb927e3de |
254 changed files with 1325 additions and 11890 deletions
|
|
@ -6,14 +6,14 @@ and your own place in it) instead of an invite list. Mobile first.
|
|||
|
||||
**Live now:** the Cinny engine (matrix-js-sdk, Rust crypto, sync) under a
|
||||
Ratatoskr UI: branding, GameCult theme, estate navigation, pose portraits
|
||||
(opt-in setting), a background scene (on in the dev config, `backgroundScene.tier`; the device can lower it) and an opt-in soundscape.
|
||||
(opt-in setting) and a background scene (on in the dev config, `backgroundScene.tier`; the device can lower it).
|
||||
**Planned:** see [`docs/gamecult/ratatoskr-target.md`](docs/gamecult/ratatoskr-target.md)
|
||||
for the target and cut sequence. Internal names that are protocol or stored
|
||||
state (`cinny_*` localStorage keys, the `in.cinny.room.power_level_tags` event
|
||||
type, `CINNY_BASE`) are unchanged on purpose.
|
||||
|
||||
Entry points: `src/app/` (client UI), `src/app/features/scene/` (background
|
||||
scene), `src/app/features/soundscape/` (audio socket), `harness/` (estate
|
||||
scene), `harness/` (estate
|
||||
drive scripts), `scripts/gen-brand.mjs` (regenerates the logo and icons).
|
||||
|
||||
## Upstream
|
||||
|
|
|
|||
|
|
@ -19,8 +19,7 @@
|
|||
"basename": "/"
|
||||
},
|
||||
"backgroundScene": {
|
||||
"tier": "full",
|
||||
"style": "ridge"
|
||||
"tier": "full"
|
||||
},
|
||||
"dings": {
|
||||
"enabled": false
|
||||
|
|
|
|||
|
|
@ -1,25 +1,9 @@
|
|||
# Scene harness
|
||||
|
||||
Compiles, renders and times the background scene (`src/app/features/scene/`) in headless
|
||||
Renders and times the ridge background scene (`src/app/features/scene/ridge/`) in headless
|
||||
Chromium. Not shipped, not run by CI.
|
||||
|
||||
node bundle.cjs <outdir> # esbuild bundle of entry.ts plus an index.html
|
||||
node drive.cjs <outdir> compile # compile and link each stage, JSON report
|
||||
node drive.cjs <outdir> shots <pngdir> # rest, mid pull-back and pulled-back screenshots
|
||||
node gradAxis.cjs <shaders dir> # numeric check that noise gradients are (d/dx, d/dz-as-.y, ...): terrainNormal axis
|
||||
node drive.cjs <outdir> measure # GPU time per pass by timer query, two viewports, two levels
|
||||
node drive.cjs <outdir> variants # the same with source patches (no erosion, no tree, value-only fbm)
|
||||
node drive.cjs <outdir> trace # mean trace steps per pixel and pass ms at three camera poses, PREPASS=0,1 arms
|
||||
node drive.cjs <outdir> diff <pngdir> # one frozen frame with and without the prepass, pixel diff and both PNGs
|
||||
node drive.cjs <outdir> phacelle # the Phacelle gradient probe behind world.ts `phacelleGradBound`
|
||||
|
||||
Needs `esbuild` and `playwright@1.48.2` on `NODE_PATH` and a Chromium. The first run was done on a
|
||||
host with no GPU, so `drive.cjs` launches with `--use-angle=swiftshader` (software Vulkan). On a
|
||||
machine with a GPU, remove those flags to measure the real device. `bundle.cjs` must run from a
|
||||
directory whose ancestors hold no empty `package.json` (esbuild reads them).
|
||||
|
||||
Timings from SwiftShader are CPU time: use them for the split between passes and for before and
|
||||
after of one change, never as a phone frame time.
|
||||
node bundle.cjs <outdir> # esbuild bundle of ridgeDemo.ts plus an index.html
|
||||
|
||||
## Ridge live scene
|
||||
|
||||
|
|
@ -43,20 +27,17 @@ clamped to the place's range as the app does (phi 0: `camera.r_max_forward_m`, a
|
|||
|
||||
npx vite --port 5199 # from the repo root; the app's vite config serves the page and public/
|
||||
http://localhost:5199/harness/scene/ridgeSheet.html # four presets x six skies
|
||||
...ridgeSheet.html?preset=swiss # one preset (physical|swiss|poster|painterly)
|
||||
...ridgeSheet.html?preset=painterly # one preset (painterly|painterly-cel-2|painterly-cel-3|painterly-cel-4)
|
||||
...ridgeSheet.html?looks=%5B%7B%22label%22%3A%22no-ink%22%2C%22inkScale%22%3A0%7D%2C%7B%22label%22%3A%22hazy%22%2C%22hazeScale%22%3A8%7D%5D
|
||||
...?w=640 # cell width
|
||||
|
||||
`looks=` is a url-encoded or base64 JSON array of `{label, ...partial RidgeLook}` and replaces the preset rows (`inkKeep` and `reliefLight` merge by key).
|
||||
`looks=` is a url-encoded or base64 JSON array of `{label, ...partial RidgeLook}` and replaces the preset rows (`inkKeep` merges by key).
|
||||
A cell costs one WebGL2 context and a card decode, so the full sheet takes tens of seconds (much longer in a background tab).
|
||||
|
||||
Presets (`PRESETS` in `ridgeSheet.ts`; swiss and poster take every key not named from `PHYSICAL_LOOK`, the rest from `DEFAULT_LOOK`, the painterly cel look), chosen by reasoning, not by eye, for Self to tune:
|
||||
Presets (`PRESETS` in `ridgeSheet.ts`; every key not named comes from `DEFAULT_LOOK`, the painterly cel-3 look), chosen by reasoning, not by eye, for Self to tune:
|
||||
|
||||
| preset | values |
|
||||
| --- | --- |
|
||||
| physical | PHYSICAL_LOOK (Lambert, no noise, sky haze, full ink) |
|
||||
| swiss | reliefLight {mix 0.7, azimuthDeg -45, elevationDeg 40}, contrastByDistance 0.9, hazeScale 6, hazeTint [0, 0.05, 0.25], nearWarm 0.5, inkScale 0.6 |
|
||||
| poster | reliefWeight 0.15, cardToneStep 0.25, cardGradient 0.5, inkKeep {edge 0.25, occlude 0.9, crease 1}, hazeScale 4 |
|
||||
| painterly | DEFAULT_LOOK: groundNoise 0.35, cloudShadows 0.5, nearWarm 0.6, hazeScale 2, inkScale 0.4, celBands 3, celSoftness 0.05, celAmbientAway 0.7 |
|
||||
| painterly-cel-2 / -3 / -4 | painterly with celBands 2 / 3 / 4 |
|
||||
|
||||
|
|
|
|||
|
|
@ -1,50 +1,22 @@
|
|||
// Bundles entry.ts with the scene's ?raw GLSL imports into $OUT/bundle.js plus an index.html.
|
||||
// usage: node bundle.cjs <outdir> [demo|ridge] (esbuild from NODE_PATH). `demo` bundles the ray-march
|
||||
// standalone page; `ridge` the ridge scene's page (open it with ?probe=1 for the cadence readout).
|
||||
// Bundles ridgeDemo.ts into $OUT/bundle.js plus an index.html.
|
||||
// usage: node bundle.cjs <outdir> (esbuild from NODE_PATH).
|
||||
const esbuild = require('esbuild');
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const out = process.argv[2];
|
||||
const demo = process.argv[3] === 'demo';
|
||||
const ridge = process.argv[3] === 'ridge';
|
||||
fs.mkdirSync(out, { recursive: true });
|
||||
const rawPlugin = {
|
||||
name: 'raw',
|
||||
setup(b) {
|
||||
b.onResolve({ filter: /\?raw$/ }, (a) => ({
|
||||
path: path.resolve(a.resolveDir, a.path.slice(0, -4)),
|
||||
namespace: 'raw',
|
||||
}));
|
||||
b.onLoad({ filter: /.*/, namespace: 'raw' }, (a) => ({
|
||||
contents: fs.readFileSync(a.path, 'utf8'),
|
||||
loader: 'text',
|
||||
}));
|
||||
},
|
||||
};
|
||||
esbuild
|
||||
.build({
|
||||
entryPoints: [path.join(__dirname, ridge ? 'ridgeDemo.ts' : demo ? 'demo.ts' : 'entry.ts')],
|
||||
entryPoints: [path.join(__dirname, 'ridgeDemo.ts')],
|
||||
bundle: true,
|
||||
outfile: path.join(out, 'bundle.js'),
|
||||
plugins: [rawPlugin],
|
||||
format: 'iife',
|
||||
target: 'es2020',
|
||||
define: { 'import.meta.env.BASE_URL': '"/"' },
|
||||
})
|
||||
.then(() => {
|
||||
if (ridge) {
|
||||
fs.writeFileSync(
|
||||
path.join(out, 'index.html'),
|
||||
'<!doctype html><meta charset=utf-8><meta name=viewport content="width=device-width,initial-scale=1"><title>Ratatoskr ridge scene</title><body style="margin:0;background:#07111a"><div id=stage style="position:relative;width:100vw;height:100vh;overflow:hidden"><canvas id=c style="width:100%;height:100%;display:block"></canvas></div><script src=bundle.js></script>'
|
||||
);
|
||||
return;
|
||||
}
|
||||
fs.writeFileSync(
|
||||
path.join(out, 'index.html'),
|
||||
'<!doctype html><meta charset=utf-8><title>Ratatoskr scene: trace prepass</title><body style="margin:0;background:#000"><canvas id=c style="width:100vw;height:100vh;display:block"></canvas>' +
|
||||
(demo
|
||||
? '<div style="position:fixed;left:8px;top:8px;padding:6px 8px;background:#000a;color:#ddd;font:12px monospace"><label><input id=prepass type=checkbox checked> cone prepass</label> <label><input id=half type=checkbox> half-float start</label> <label>pull-back <input id=pull type=range min=0 max=1 step=0.05 value=0.6></label><pre id=out style="margin:4px 0 0;white-space:pre-wrap"></pre><details id=dev><summary>device</summary><pre id=info style="margin:4px 0 0;white-space:pre-wrap;max-height:50vh;overflow:auto"></pre></details></div>'
|
||||
: '') +
|
||||
'<script src=bundle.js></script>'
|
||||
'<!doctype html><meta charset=utf-8><meta name=viewport content="width=device-width,initial-scale=1"><title>Ratatoskr ridge scene</title><body style="margin:0;background:#07111a"><div id=stage style="position:relative;width:100vw;height:100vh;overflow:hidden"><canvas id=c style="width:100%;height:100%;display:block"></canvas></div><script src=bundle.js></script>'
|
||||
);
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,102 +0,0 @@
|
|||
// Standalone page: the scene full-window with a readout of pass ms and trace steps per pixel, and
|
||||
// a switch for the cone prepass. Not shipped.
|
||||
import {
|
||||
createScene,
|
||||
Scene,
|
||||
SceneStats,
|
||||
SceneUnavailable,
|
||||
TraceStats,
|
||||
} from '../../src/app/features/scene/Scene';
|
||||
import { LEVELS } from '../../src/app/features/scene/budget';
|
||||
|
||||
let canvas = document.getElementById('c') as HTMLCanvasElement;
|
||||
const out = document.getElementById('out') as HTMLPreElement;
|
||||
const box = document.getElementById('prepass') as HTMLInputElement;
|
||||
const pull = document.getElementById('pull') as HTMLInputElement;
|
||||
const half = document.getElementById('half') as HTMLInputElement;
|
||||
const dev = document.getElementById('dev') as HTMLDetailsElement;
|
||||
const info = document.getElementById('info') as HTMLPreElement;
|
||||
const timerless = (() => {
|
||||
const g = document.createElement('canvas').getContext('webgl2');
|
||||
return !g?.getExtension('EXT_disjoint_timer_query_webgl2');
|
||||
})();
|
||||
|
||||
const WHY: Record<SceneUnavailable, string> = {
|
||||
'no-webgl2': 'this browser gave no WebGL2 context',
|
||||
'no-float-or-half-float-colour-buffer':
|
||||
'WebGL2 is there, but neither EXT_color_buffer_float nor EXT_color_buffer_half_float is',
|
||||
};
|
||||
|
||||
// What the browser says about itself, read from a scratch context so it shows even when the scene
|
||||
// could not start. A canvas that never got a WebGL2 context is asked for WebGL1 to name the GPU.
|
||||
function describeDevice(): string {
|
||||
const c = document.createElement('canvas');
|
||||
const gl2 = c.getContext('webgl2');
|
||||
const gl = gl2 ?? (document.createElement('canvas').getContext('webgl') as WebGLRenderingContext | null);
|
||||
const lines = [`webgl2 context: ${gl2 ? 'yes' : 'NO'}`];
|
||||
if (!gl) return [...lines, 'webgl1 context: NO'].join('\n');
|
||||
const dbg = gl.getExtension('WEBGL_debug_renderer_info');
|
||||
lines.push(
|
||||
`renderer: ${gl.getParameter(dbg ? dbg.UNMASKED_RENDERER_WEBGL : gl.RENDERER)}`,
|
||||
`vendor: ${gl.getParameter(dbg ? dbg.UNMASKED_VENDOR_WEBGL : gl.VENDOR)}`,
|
||||
`version: ${gl.getParameter(gl.VERSION)}`,
|
||||
`user agent: ${navigator.userAgent}`
|
||||
);
|
||||
const ext = gl.getSupportedExtensions() ?? [];
|
||||
for (const n of ['EXT_color_buffer_float', 'EXT_color_buffer_half_float', 'OES_texture_float_linear', 'EXT_disjoint_timer_query_webgl2'])
|
||||
lines.push(`${n}: ${ext.includes(n) ? 'yes' : 'NO'}`);
|
||||
lines.push(`extensions (${ext.length}): ${ext.join(' ')}`);
|
||||
return lines.join('\n');
|
||||
}
|
||||
info.textContent = describeDevice();
|
||||
|
||||
let scene: Scene | null = null;
|
||||
let stats: SceneStats | undefined;
|
||||
let trace: TraceStats | undefined;
|
||||
|
||||
function start() {
|
||||
scene?.dispose();
|
||||
stats = trace = undefined;
|
||||
// A fresh canvas: a context cannot change its attributes, and dispose leaves the old one bound.
|
||||
const fresh = canvas.cloneNode() as HTMLCanvasElement;
|
||||
canvas.replaceWith(fresh);
|
||||
canvas = fresh;
|
||||
scene = createScene({
|
||||
canvas: fresh,
|
||||
unthrottled: true,
|
||||
fixedLevel: LEVELS[0],
|
||||
fixedPull: +pull.value,
|
||||
prepass: box.checked,
|
||||
halfStart: half.checked,
|
||||
onUnavailable: (r) => (out.textContent = `createScene returned null: ${WHY[r]}`),
|
||||
onCompileFail: (e) => (out.textContent = `createScene returned null: ${e.message}`),
|
||||
onStats: (s) => (stats = s),
|
||||
onTraceStats: (t) => (trace = t),
|
||||
});
|
||||
dev.open = !scene;
|
||||
}
|
||||
|
||||
setInterval(() => {
|
||||
if (!scene) return;
|
||||
const lines = [`prepass ${box.checked ? 'on' : 'off'} start target ${scene.startFormat} pull ${pull.value}`];
|
||||
if (stats) {
|
||||
const ms = stats.passMs;
|
||||
const total = Object.values(ms).reduce((a, b) => a + b, 0);
|
||||
lines.push(
|
||||
`gpu ms prepass ${ms.prepass.toFixed(2)} terrain ${ms.terrain.toFixed(2)} atmosphere ${ms.atmosphere.toFixed(2)} resolve ${ms.resolve.toFixed(2)} composite ${ms.composite.toFixed(2)} total ${total.toFixed(2)}`,
|
||||
`solid ${stats.solidSize.join('x')}`
|
||||
);
|
||||
} else if (timerless) {
|
||||
lines.push('gpu ms: this browser has no EXT_disjoint_timer_query_webgl2');
|
||||
}
|
||||
if (trace)
|
||||
lines.push(
|
||||
`steps/pixel ${trace.stepsPerPixel.toFixed(2)} (pass 1 ${trace.traceSteps.toFixed(2)}, prepass ${trace.prepassSteps.toFixed(1)} per tile)`
|
||||
);
|
||||
out.textContent = lines.join('\n');
|
||||
}, 500);
|
||||
|
||||
box.addEventListener('change', start);
|
||||
half.addEventListener('change', start);
|
||||
pull.addEventListener('input', start);
|
||||
start();
|
||||
|
|
@ -1,309 +0,0 @@
|
|||
// Drives the scene in headless Chromium (software GL unless the host has a GPU).
|
||||
// usage: node drive.cjs <bundledir> <mode> [outdir] modes: compile | shots | measure
|
||||
// Needs playwright from NODE_PATH and PLAYWRIGHT_BROWSERS_PATH. Prints one JSON report.
|
||||
const { chromium } = require('playwright');
|
||||
const path = require('path');
|
||||
const fs = require('fs');
|
||||
const [, , dir, mode, outdir = '.'] = process.argv;
|
||||
|
||||
(async () => {
|
||||
const b = await chromium.launch({
|
||||
args: [
|
||||
'--use-gl=angle',
|
||||
'--use-angle=swiftshader',
|
||||
'--enable-unsafe-swiftshader',
|
||||
'--ignore-gpu-blocklist',
|
||||
],
|
||||
});
|
||||
const page = await b.newPage({ viewport: { width: 960, height: 540 } });
|
||||
page.on('pageerror', (e) => process.stderr.write(`[pageerror] ${e}\n`));
|
||||
page.on('console', (m) => process.stderr.write(`[page] ${m.text()}\n`));
|
||||
await page.goto('file://' + path.resolve(dir, 'index.html'));
|
||||
const report = { mode };
|
||||
report.renderer = await page.evaluate(() => {
|
||||
const g = document.createElement('canvas').getContext('webgl2');
|
||||
const e = g.getExtension('WEBGL_debug_renderer_info');
|
||||
return g.getParameter(e ? e.UNMASKED_RENDERER_WEBGL : g.RENDERER);
|
||||
});
|
||||
|
||||
if (mode === 'compile') {
|
||||
report.stages = await page.evaluate(() => {
|
||||
const gl = document.createElement('canvas').getContext('webgl2');
|
||||
const S = window.__scene;
|
||||
return ['terrain', 'atmosphere', 'resolve', 'composite'].map((stage) => {
|
||||
const t0 = performance.now();
|
||||
try {
|
||||
const p = S.linkStage(gl, stage);
|
||||
return {
|
||||
stage,
|
||||
ok: true,
|
||||
ms: +(performance.now() - t0).toFixed(1),
|
||||
sourceBytes: S.fragmentSource(stage).length,
|
||||
log: gl.getProgramInfoLog(p),
|
||||
};
|
||||
} catch (e) {
|
||||
return {
|
||||
stage,
|
||||
ok: false,
|
||||
ms: +(performance.now() - t0).toFixed(1),
|
||||
log: String(e.log || e),
|
||||
};
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
if (mode === 'phacelle') {
|
||||
report.probe = await page.evaluate(() =>
|
||||
window.__probePhacelle(
|
||||
window.__scene.WORLD.erodeSide.slice(),
|
||||
window.__scene.WORLD.erodeNorm,
|
||||
4
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
if (mode === 'shots') {
|
||||
await page.evaluate(() => {
|
||||
const c = document.getElementById('c');
|
||||
window.__s = window.__scene.createScene({
|
||||
canvas: c,
|
||||
unthrottled: true,
|
||||
fixedLevel: window.__scene.LEVELS[0],
|
||||
});
|
||||
});
|
||||
const wait = (ms) => page.waitForTimeout(ms);
|
||||
await wait(4000);
|
||||
await page.screenshot({ path: path.join(outdir, 'rest.png') });
|
||||
await page.evaluate(() => window.__s.login());
|
||||
await wait(3500);
|
||||
await page.screenshot({ path: path.join(outdir, 'mid-pullback.png') });
|
||||
await wait(9000);
|
||||
await page.screenshot({ path: path.join(outdir, 'pulled-back.png') });
|
||||
report.shots = ['rest.png', 'mid-pullback.png', 'pulled-back.png'];
|
||||
}
|
||||
|
||||
if (mode === 'measure' || mode === 'variants') {
|
||||
const VARIANTS = {
|
||||
baseline: null,
|
||||
// What a public value-only fbm would cost: the same octaves without the gradient work.
|
||||
valueOnlyFbm: [
|
||||
'float terrainFbm(vec2 xz) { return cultmath_fbm_grad(vec3(xz * W_FREQ, 0.0), W_OCTAVES, W_LACUNARITY, W_GAIN).w; }',
|
||||
'float terrainFbm(vec2 xz) { float a = 1.0, fr = 1.0, v = 0.0; for (int i = 0; i < W_OCTAVES; i++) { v += a * cultmath_snoise(vec3(xz * W_FREQ * fr, 0.0)); fr *= W_LACUNARITY; a *= W_GAIN; } return v; }',
|
||||
],
|
||||
noErosion: ['#define W_ERODE_ENABLED 1', '#define W_ERODE_ENABLED 0'],
|
||||
// Upper bound on what skipping sky rays would save: every upward ray misses at once.
|
||||
noSkyMarch: [' bool hit = false;\n bool onTree = false;', ' if (rd.y > 0.0) { o_color = vec4(0.0); o_depth = W_FAR; return; }\n bool hit = false;\n bool onTree = false;'],
|
||||
noTree: ['float dr = treeDistance(p, leafness);', 'float dr = 1e9; leafness = 0.0;'],
|
||||
};
|
||||
const wanted = mode === "variants" ? (process.env.ONLY ? process.env.ONLY.split(",") : Object.keys(VARIANTS)) : ['baseline'];
|
||||
const sizes = [
|
||||
[960, 540],
|
||||
[540, 1200],
|
||||
];
|
||||
report.runs = [];
|
||||
for (const [w, h] of sizes) {
|
||||
for (const [li, variant] of wanted.flatMap((v) =>
|
||||
mode === 'variants'
|
||||
? [[0, v]]
|
||||
: [
|
||||
[0, v],
|
||||
[3, v],
|
||||
]
|
||||
)) {
|
||||
await page.setViewportSize({ width: w, height: h });
|
||||
const r = await page.evaluate(
|
||||
({ li, rep }) =>
|
||||
new Promise((res) => {
|
||||
const rows = [];
|
||||
const c = document.getElementById('c');
|
||||
const s = window.__scene.createScene({
|
||||
canvas: c,
|
||||
unthrottled: true,
|
||||
fixedLevel: window.__scene.LEVELS[li],
|
||||
patchSource: rep
|
||||
? (st, src) =>
|
||||
st === 'terrain'
|
||||
? rep[0].startsWith('#define')
|
||||
? src.replace(/#define W_ERODE_ENABLED \d/, rep[1])
|
||||
: src.split(rep[0]).join(rep[1])
|
||||
: src
|
||||
: undefined,
|
||||
onStats: (st) => {
|
||||
rows.push(st);
|
||||
if (rows.length === 40) {
|
||||
s.dispose();
|
||||
const keep = rows.slice(10);
|
||||
const med = (k) =>
|
||||
keep.map((x) => x.passMs[k]).sort((a, b) => a - b)[keep.length >> 1];
|
||||
res({
|
||||
solid: keep[0].solidSize,
|
||||
atm: keep[0].atmosphereSize,
|
||||
medianMs: {
|
||||
terrain: med('terrain'),
|
||||
atmosphere: med('atmosphere'),
|
||||
resolve: med('resolve'),
|
||||
composite: med('composite'),
|
||||
},
|
||||
});
|
||||
}
|
||||
},
|
||||
});
|
||||
if (!s) res({ error: 'createScene returned null' });
|
||||
}),
|
||||
{ li, rep: VARIANTS[variant] }
|
||||
);
|
||||
report.runs.push({ viewport: [w, h], level: li, variant, ...r });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (mode === 'trace') {
|
||||
// Steps per pixel and pass ms at fixed camera poses, one scene per run. PREPASS=0,1 picks the arms.
|
||||
const arms = (process.env.PREPASS || '1').split(',').map((x) => x === '1');
|
||||
report.runs = [];
|
||||
for (const [w, h] of process.env.PORTRAIT === '0'
|
||||
? [[960, 540]]
|
||||
: [
|
||||
[960, 540],
|
||||
[540, 1200],
|
||||
]) {
|
||||
for (const pull of (process.env.PULLS || '0,0.5,1').split(',').map(Number)) {
|
||||
for (const prepass of arms) {
|
||||
await page.setViewportSize({ width: w, height: h });
|
||||
const r = await page.evaluate(
|
||||
({ pull, prepass, FRAMES }) =>
|
||||
new Promise((res) => {
|
||||
const rows = [];
|
||||
const trace = [];
|
||||
let done = false;
|
||||
const finish = () => {
|
||||
if (done || rows.length < FRAMES || trace.length < 4) return;
|
||||
done = true;
|
||||
s.dispose();
|
||||
const keep = rows.slice(FRAMES >> 2);
|
||||
const med = (xs) => xs.sort((a, b) => a - b)[xs.length >> 1];
|
||||
const tk = trace.slice(1);
|
||||
const mean = (k) => tk.reduce((a, t) => a + t[k], 0) / tk.length;
|
||||
res({
|
||||
solid: keep[0].solidSize,
|
||||
readbacks: tk.length,
|
||||
traceSteps: +mean('traceSteps').toFixed(2),
|
||||
prepassSteps: +mean('prepassSteps').toFixed(2),
|
||||
stepsPerPixel: +mean('stepsPerPixel').toFixed(2),
|
||||
medianMs: Object.fromEntries(
|
||||
Object.keys(keep[0].passMs).map((k) => [k, +med(keep.map((x) => x.passMs[k])).toFixed(2)])
|
||||
),
|
||||
});
|
||||
};
|
||||
const s = window.__scene.createScene({
|
||||
canvas: document.getElementById('c'),
|
||||
unthrottled: true,
|
||||
fixedLevel: window.__scene.LEVELS[0],
|
||||
fixedPull: pull,
|
||||
prepass,
|
||||
onTraceStats: (t) => {
|
||||
trace.push(t);
|
||||
finish();
|
||||
},
|
||||
onStats: (st) => {
|
||||
rows.push(st);
|
||||
finish();
|
||||
},
|
||||
});
|
||||
if (!s) res({ error: 'createScene returned null' });
|
||||
}),
|
||||
{ pull, prepass, FRAMES: +(process.env.FRAMES || 64) }
|
||||
);
|
||||
report.runs.push({ viewport: [w, h], pull, prepass, ...r });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (mode === 'diff') {
|
||||
// Same frozen frame (reduced motion: time 0, 32 frames) with and without the prepass, compared
|
||||
// pixel by pixel. The prepass is meant to change cost, not the picture.
|
||||
await page.emulateMedia({ reducedMotion: 'reduce' });
|
||||
await page.setViewportSize({ width: 640, height: 360 });
|
||||
const shoot = async (pull, prepass, steps) => {
|
||||
await page.evaluate(
|
||||
({ pull, prepass, steps }) => {
|
||||
// Reduced motion bounds the scene to 32 frames; each asks for the next with rAF, so the
|
||||
// count stops moving when it is done. Timer-query callbacks lag too far to count on.
|
||||
window.__raf = 0;
|
||||
if (!window.__rafPatched) {
|
||||
window.__rafPatched = true;
|
||||
const raf = window.requestAnimationFrame.bind(window);
|
||||
window.requestAnimationFrame = (cb) => (window.__raf++, raf(cb));
|
||||
}
|
||||
window.__d = window.__scene.createScene({
|
||||
canvas: document.getElementById('c'),
|
||||
fixedLevel: { ...window.__scene.LEVELS[0], traceSteps: steps },
|
||||
fixedPull: pull,
|
||||
prepass,
|
||||
});
|
||||
},
|
||||
{ pull, prepass, steps }
|
||||
);
|
||||
for (let last = -1, still = 0; still < 3; await page.waitForTimeout(1000)) {
|
||||
const n = await page.evaluate(() => window.__raf);
|
||||
still = n === last ? still + 1 : 0;
|
||||
last = n;
|
||||
}
|
||||
const png = await page.screenshot();
|
||||
await page.evaluate(() => window.__d.dispose());
|
||||
return png.toString('base64');
|
||||
};
|
||||
// The step cap makes a grazing ray give up and count as a hit, so the baseline is compared
|
||||
// with a 512-step render of the same frame as well: whichever is closer to it is the more
|
||||
// faithful one.
|
||||
const decode = (x) =>
|
||||
page.evaluate(
|
||||
(x) =>
|
||||
new Promise((r) => {
|
||||
const i = new Image();
|
||||
i.onload = () => {
|
||||
const c = document.createElement('canvas');
|
||||
c.width = i.width;
|
||||
c.height = i.height;
|
||||
const g = c.getContext('2d');
|
||||
g.drawImage(i, 0, 0);
|
||||
r(Array.from(g.getImageData(0, 0, i.width, i.height).data));
|
||||
};
|
||||
i.src = 'data:image/png;base64,' + x;
|
||||
}),
|
||||
x
|
||||
);
|
||||
const compare = (da, db) => {
|
||||
let max = 0, over = 0, sum = 0;
|
||||
const px = da.length / 4;
|
||||
for (let i = 0; i < da.length; i += 4) {
|
||||
let m = 0;
|
||||
for (let k = 0; k < 3; k++) m = Math.max(m, Math.abs(da[i + k] - db[i + k]));
|
||||
sum += m;
|
||||
if (m > max) max = m;
|
||||
if (m > 2) over++;
|
||||
}
|
||||
return { maxChannelDiff: max, pixelsOver2of255: over, ofPixels: px, meanMaxChannelDiff: +(sum / px).toFixed(3) };
|
||||
};
|
||||
report.diffs = [];
|
||||
for (const pull of (process.env.PULLS || '0,0.5,1').split(',').map(Number)) {
|
||||
const png = {
|
||||
off: await shoot(pull, false, 96),
|
||||
on: await shoot(pull, true, 96),
|
||||
ref: await shoot(pull, false, 512),
|
||||
off2: await shoot(pull, false, 96),
|
||||
};
|
||||
for (const k of Object.keys(png)) fs.writeFileSync(path.join(outdir, `diff-${k}-${pull}.png`), Buffer.from(png[k], 'base64'));
|
||||
const [off, on, ref, off2] = [await decode(png.off), await decode(png.on), await decode(png.ref), await decode(png.off2)];
|
||||
report.diffs.push({ pull, offVsOffAgain: compare(off, off2), offVsOn: compare(off, on), offVsRef512: compare(off, ref), onVsRef512: compare(on, ref) });
|
||||
}
|
||||
}
|
||||
|
||||
console.log(JSON.stringify(report, null, 1));
|
||||
await b.close();
|
||||
})().catch((e) => {
|
||||
console.log('ERR', String(e).slice(0, 2000));
|
||||
process.exit(1);
|
||||
});
|
||||
|
|
@ -1,87 +0,0 @@
|
|||
// Browser entry for the harness: exposes the scene's seams to the driver. Not shipped.
|
||||
import { createScene, linkStage, ShaderCompileError } from '../../src/app/features/scene/Scene';
|
||||
import { LEVELS } from '../../src/app/features/scene/budget';
|
||||
import { fragmentSource } from '../../src/app/features/scene/shaderSource';
|
||||
import { WORLD } from '../../src/app/features/scene/world';
|
||||
|
||||
(window as unknown as Record<string, unknown>).__scene = {
|
||||
createScene,
|
||||
linkStage,
|
||||
ShaderCompileError,
|
||||
LEVELS,
|
||||
fragmentSource,
|
||||
WORLD,
|
||||
};
|
||||
|
||||
// ---- Phacelle gradient probe -----------------------------------------------------------------
|
||||
import cultmath from '../../src/app/features/scene/shaders/CultMath.glsl?raw';
|
||||
import phacelle from '../../src/app/features/scene/shaders/CultMath.Phacelle.glsl?raw';
|
||||
import { vertexSource } from '../../src/app/features/scene/shaderSource';
|
||||
|
||||
const PROBE_FRAG = `#version 300 es
|
||||
precision highp float; precision highp int;
|
||||
${cultmath}
|
||||
${phacelle}
|
||||
uniform float u_seed; uniform vec3 u_side; uniform float u_norm; uniform float u_span;
|
||||
in vec2 v_uv; layout(location=0) out vec4 o;
|
||||
void main() {
|
||||
// The scene samples the z = 0 slice: random points in a u_span square of it.
|
||||
vec3 h = vec3(cultmath_pcg3d(vec3(gl_FragCoord.xy, u_seed))) ;
|
||||
vec2 xy = vec2(float(uint(int(h.x)) >> 8), float(uint(int(h.y)) >> 8)) * (1.0 / 16777216.0) * u_span;
|
||||
CultPhasor ph = cultmath_phacelle(vec3(xy, 0.0), u_side, 0.0, u_norm);
|
||||
o = vec4(length(ph.cos.xyz), length(ph.sin.xyz), ph.cos.w, ph.sin.w);
|
||||
}`;
|
||||
|
||||
/** Max |grad| of the phasor over `draws * 1024^2` random points; min/max of the cos component. */
|
||||
(window as unknown as Record<string, unknown>).__probePhacelle = (
|
||||
side: number[],
|
||||
norm: number,
|
||||
draws: number
|
||||
) => {
|
||||
const c = document.createElement('canvas');
|
||||
const gl = c.getContext('webgl2')!;
|
||||
gl.getExtension('EXT_color_buffer_float');
|
||||
const mk = (t: number, s: string) => {
|
||||
const x = gl.createShader(t)!;
|
||||
gl.shaderSource(x, s);
|
||||
gl.compileShader(x);
|
||||
if (!gl.getShaderParameter(x, gl.COMPILE_STATUS)) throw new Error(gl.getShaderInfoLog(x)!);
|
||||
return x;
|
||||
};
|
||||
const p = gl.createProgram()!;
|
||||
gl.attachShader(p, mk(gl.VERTEX_SHADER, vertexSource));
|
||||
gl.attachShader(p, mk(gl.FRAGMENT_SHADER, PROBE_FRAG));
|
||||
gl.linkProgram(p);
|
||||
gl.useProgram(p);
|
||||
const N = 1024;
|
||||
const tex = gl.createTexture();
|
||||
gl.bindTexture(gl.TEXTURE_2D, tex);
|
||||
gl.texStorage2D(gl.TEXTURE_2D, 1, gl.RGBA32F, N, N);
|
||||
const fbo = gl.createFramebuffer();
|
||||
gl.bindFramebuffer(gl.FRAMEBUFFER, fbo);
|
||||
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, tex, 0);
|
||||
gl.viewport(0, 0, N, N);
|
||||
gl.bindVertexArray(gl.createVertexArray());
|
||||
gl.uniform3fv(gl.getUniformLocation(p, 'u_side'), side);
|
||||
gl.uniform1f(gl.getUniformLocation(p, 'u_norm'), norm);
|
||||
gl.uniform1f(gl.getUniformLocation(p, 'u_span'), 400);
|
||||
const buf = new Float32Array(N * N * 4);
|
||||
let gradCos = 0,
|
||||
gradSin = 0,
|
||||
vMin = 1e9,
|
||||
vMax = -1e9,
|
||||
n = 0;
|
||||
for (let d = 0; d < draws; d++) {
|
||||
gl.uniform1f(gl.getUniformLocation(p, 'u_seed'), d + 1);
|
||||
gl.drawArrays(gl.TRIANGLES, 0, 3);
|
||||
gl.readPixels(0, 0, N, N, gl.RGBA, gl.FLOAT, buf);
|
||||
for (let i = 0; i < buf.length; i += 4) {
|
||||
if (buf[i] > gradCos) gradCos = buf[i];
|
||||
if (buf[i + 1] > gradSin) gradSin = buf[i + 1];
|
||||
if (buf[i + 2] < vMin) vMin = buf[i + 2];
|
||||
if (buf[i + 2] > vMax) vMax = buf[i + 2];
|
||||
n++;
|
||||
}
|
||||
}
|
||||
return { samples: n, maxGradCos: gradCos, maxGradSin: gradSin, minCos: vMin, maxCos: vMax };
|
||||
};
|
||||
|
|
@ -1,30 +0,0 @@
|
|||
// Probe: the gradient cultmath_fbm_grad / cultmath_phacelle return for vec3(xz * f, c) is (d/dx, d/dz, d/dc, value),
|
||||
// so the world-z slope is .y, not .z. Compares analytic gradients with central differences at one point.
|
||||
// Usage (playwright + swiftshader): node harness/scene/gradAxis.cjs <repo>/src/app/features/scene/shaders
|
||||
const { chromium } = require('playwright'); const fs=require('fs');
|
||||
const S=process.argv[2];
|
||||
const cm=fs.readFileSync(S+'/CultMath.glsl','utf8'), ph=fs.readFileSync(S+'/CultMath.Phacelle.glsl','utf8');
|
||||
const fs_=`#version 300 es
|
||||
precision highp float; precision highp int;
|
||||
${cm}
|
||||
${ph}
|
||||
out vec4 o;
|
||||
const float F=1.0/520.0;
|
||||
float fb(vec2 p){return cultmath_fbm_grad(vec3(p*F,0.0),4,2.0,0.45).w;}
|
||||
float pc(vec2 p){return cultmath_phacelle(vec3(p/40.0,0.5),vec3(1.5,0.5,0.0),0.0,0.5).cos.w;}
|
||||
void main(){
|
||||
vec2 p=vec2(1234.5,-777.7); float e=0.5;
|
||||
int k=int(gl_FragCoord.x);
|
||||
if(k==0){vec4 g=cultmath_fbm_grad(vec3(p*F,0.0),4,2.0,0.45); o=vec4(g.xyz*F,0.0);} // analytic per metre: x,y,z
|
||||
else if(k==1){o=vec4((fb(p+vec2(e,0))-fb(p-vec2(e,0)))/(2.0*e),(fb(p+vec2(0,e))-fb(p-vec2(0,e)))/(2.0*e),0,0);}
|
||||
else if(k==2){vec4 g=cultmath_phacelle(vec3(p/40.0,0.5),vec3(1.5,0.5,0.0),0.0,0.5).cos; o=vec4(g.xyz/40.0,0.0);}
|
||||
else {o=vec4((pc(p+vec2(e,0))-pc(p-vec2(e,0)))/(2.0*e),(pc(p+vec2(0,e))-pc(p-vec2(0,e)))/(2.0*e),0,0);}
|
||||
}`;
|
||||
(async()=>{const b=await chromium.launch({args:['--use-gl=angle','--use-angle=swiftshader','--enable-unsafe-swiftshader']});
|
||||
const pg=await b.newPage();
|
||||
const r=await pg.evaluate(([src])=>{const c=document.createElement('canvas');const g=c.getContext('webgl2');g.getExtension('EXT_color_buffer_float');
|
||||
const mk=(t,s)=>{const x=g.createShader(t);g.shaderSource(x,s);g.compileShader(x);if(!g.getShaderParameter(x,g.COMPILE_STATUS))throw g.getShaderInfoLog(x);return x};
|
||||
const p=g.createProgram();g.attachShader(p,mk(g.VERTEX_SHADER,'#version 300 es\nvoid main(){vec2 p=vec2(float((gl_VertexID<<1)&2),float(gl_VertexID&2));gl_Position=vec4(p*2.0-1.0,0.0,1.0);}'));g.attachShader(p,mk(g.FRAGMENT_SHADER,src));g.linkProgram(p);g.useProgram(p);
|
||||
const t=g.createTexture();g.bindTexture(g.TEXTURE_2D,t);g.texImage2D(g.TEXTURE_2D,0,g.RGBA32F,4,1,0,g.RGBA,g.FLOAT,null);const f=g.createFramebuffer();g.bindFramebuffer(g.FRAMEBUFFER,f);g.framebufferTexture2D(g.FRAMEBUFFER,g.COLOR_ATTACHMENT0,g.TEXTURE_2D,t,0);g.viewport(0,0,4,1);g.drawArrays(g.TRIANGLES,0,3);
|
||||
const o=new Float32Array(16);g.readPixels(0,0,4,1,g.RGBA,g.FLOAT,o);return Array.from(o)},[fs_]).catch(e=>'ERR '+String(e).slice(0,500));
|
||||
console.log(Array.isArray(r)?['fbm analytic x,y,z','fbm FD dx,dz','phac analytic','phac FD'].map((n,i)=>n+': '+r.slice(i*4,i*4+3).map(v=>v.toExponential(3)).join(' ')).join('\n'):r);await b.close()})();
|
||||
|
|
@ -1,6 +1,5 @@
|
|||
// Standalone page for the ridge scene: full window, no host app. `?tier=still|low|full` picks the
|
||||
// tier, `?probe=1` shows the rAF median/p95 readout. The long tasks the page saw are on `window.longTasks`
|
||||
// for a driver to read. Not shipped.
|
||||
// tier. The long tasks the page saw are on `window.longTasks` for a driver to read. Not shipped.
|
||||
import { startBackgroundScene } from '../../src/app/features/scene';
|
||||
import type { SceneTier } from '../../src/app/features/scene';
|
||||
|
||||
|
|
|
|||
|
|
@ -3,8 +3,8 @@
|
|||
// `?views=214:0:200,0:0:200,100:0:200,214:90:98.2` one column per view `heading:phi:offset` (degrees, degrees, metres) at one sky (`?sky=2`, an index of SKIES, noon by default); a heading
|
||||
// of 360 or 0 is across north. `&sun=100:6` puts the sun of that sky at azimuth 100, 6 degrees up (the stars are always those of the moment the sheet is opened). The offset is clamped to the place's range as the app does (phi 0: the bake's forward bound, any other phi: the worst-case bound), and a phi other than 0 is the offset-only rotation mode, the camera circling the centre.
|
||||
// `?place=vienna` the baked place (index.json's default if absent)
|
||||
// `?preset=all|physical|swiss|poster|painterly|painterly-cel-2|painterly-cel-3|painterly-cel-4` (default all: one row each; painterly is DEFAULT_LOOK); `?looks=<JSON array, url-encoded or base64>` replaces the rows with
|
||||
// the given `{label, ...partial RidgeLook}` entries (inkKeep and reliefLight merge by key). `?w=480` sets the cell width, 16:9 unless `?h=` gives the height (`?w=375&h=812` is a phone).
|
||||
// `?preset=all|painterly|painterly-cel-2|painterly-cel-3|painterly-cel-4` (default all: one row each; painterly is DEFAULT_LOOK); `?looks=<JSON array, url-encoded or base64>` replaces the rows with
|
||||
// the given `{label, ...partial RidgeLook}` entries (inkKeep merges by key). `?w=480` sets the cell width, 16:9 unless `?h=` gives the height (`?w=375&h=812` is a phone).
|
||||
// The sky behind a cell is the app's own: `makePhysicalSky` + `paintSky` upscaled smoothly, with the real stars and the moon (`nightBodies`),
|
||||
// without the sun disc or clouds. Columns are the SKIES below (a sun elevation each, the stars and moon of the moment the sheet was opened), or:
|
||||
// `?moments=2026-11-24T22:00Z,2026-12-09T20:00Z` explicit UTC moments: the sun, moon and stars are those of the moment, the state follows the sun's elevation
|
||||
|
|
@ -12,7 +12,7 @@
|
|||
// (`?hours=18,21,0,4` UTC), plus deep dusk (sun at -10 degrees) of the evening of the full moon
|
||||
// `?labels=1` DEBUG: label each constellation chain in frame with its d3-celestial abbreviation (fetched from the source repository at run time; not shipped)
|
||||
// `?lines=1` constellation lines over the stars, as the Sky menu's hidden toggle does (night cells only)
|
||||
import { DEFAULT_LOOK, PHYSICAL_LOOK, createLighter } from '../../src/app/features/scene/ridge/lightCards';
|
||||
import { DEFAULT_LOOK, createLighter } from '../../src/app/features/scene/ridge/lightCards';
|
||||
import type { RidgeLook } from '../../src/app/features/scene/ridge/lightCards';
|
||||
import { parseIndex, parseManifest } from '../../src/app/features/scene/ridge/manifest';
|
||||
import { makePhysicalSky } from '../../src/app/features/scene/ridge/physicalSky';
|
||||
|
|
@ -28,12 +28,9 @@ import { moonPhase } from '../../src/sky/moon.js';
|
|||
import { MOMENT_IDS, momentFor } from '../../src/app/features/scene/ridge/skyMoment';
|
||||
|
||||
|
||||
type Override = Partial<Omit<RidgeLook, 'inkKeep' | 'reliefLight'>> & {
|
||||
type Override = Partial<Omit<RidgeLook, 'inkKeep'>> & {
|
||||
label: string;
|
||||
/** The look the unnamed keys come from (DEFAULT_LOOK, the painterly cel look, if absent). */
|
||||
base?: 'physical';
|
||||
inkKeep?: Partial<RidgeLook['inkKeep']>;
|
||||
reliefLight?: Partial<RidgeLook['reliefLight']>;
|
||||
};
|
||||
|
||||
interface Column {
|
||||
|
|
@ -58,26 +55,6 @@ const SKIES: Column[] = [
|
|||
|
||||
/** The art directions, chosen by reasoning, not by eye: Self tunes them (values listed in harness/scene/README.md). */
|
||||
const PRESETS: Record<string, Override> = {
|
||||
physical: { label: 'physical', base: 'physical' },
|
||||
swiss: {
|
||||
label: 'swiss',
|
||||
base: 'physical',
|
||||
reliefLight: { mix: 0.7, azimuthDeg: -45, elevationDeg: 40 },
|
||||
contrastByDistance: 0.9,
|
||||
hazeScale: 6,
|
||||
hazeTint: [0, 0.05, 0.25],
|
||||
nearWarm: 0.5,
|
||||
inkScale: 0.6,
|
||||
},
|
||||
poster: {
|
||||
label: 'poster',
|
||||
base: 'physical',
|
||||
reliefWeight: 0.15,
|
||||
cardToneStep: 0.25,
|
||||
cardGradient: 0.5,
|
||||
inkKeep: { edge: 0.25, occlude: 0.9, crease: 1 },
|
||||
hazeScale: 4,
|
||||
},
|
||||
painterly: { label: 'painterly (default, cel 3)' },
|
||||
'painterly-cel-2': { label: 'painterly-cel-2', celBands: 2 },
|
||||
'painterly-cel-3': { label: 'painterly-cel-3', celBands: 3 },
|
||||
|
|
@ -85,15 +62,13 @@ const PRESETS: Record<string, Override> = {
|
|||
};
|
||||
|
||||
const merge = (o: Override): { label: string; look: RidgeLook } => {
|
||||
const { label, base: baseName, inkKeep, reliefLight, ...rest } = o;
|
||||
const base = baseName === 'physical' ? PHYSICAL_LOOK : DEFAULT_LOOK;
|
||||
const { label, inkKeep, ...rest } = o;
|
||||
return {
|
||||
label,
|
||||
look: {
|
||||
...base,
|
||||
...DEFAULT_LOOK,
|
||||
...rest,
|
||||
inkKeep: { ...base.inkKeep, ...inkKeep },
|
||||
reliefLight: { ...base.reliefLight, ...reliefLight },
|
||||
inkKeep: { ...DEFAULT_LOOK.inkKeep, ...inkKeep },
|
||||
},
|
||||
};
|
||||
};
|
||||
|
|
@ -187,7 +162,7 @@ const pinned = q.get('moments') || q.get('night');
|
|||
const rows = (q.get('looks')
|
||||
? parseLooks(q.get('looks') as string)
|
||||
: preset && preset !== 'all'
|
||||
? [PRESETS[preset] ?? PRESETS.physical]
|
||||
? [PRESETS[preset] ?? PRESETS.painterly]
|
||||
: pinned
|
||||
? [PRESETS.painterly] // a night set is read in the default look unless a preset or looks say otherwise
|
||||
: Object.values(PRESETS)
|
||||
|
|
|
|||
|
|
@ -1,15 +1,12 @@
|
|||
// Bakes Midnight Sky and Noonday Sky from src/sky/sun.js into src/sky/baked.ts, with the
|
||||
// atmospheric-scattering tables (src/sky/scatter.js) as `scatter`.
|
||||
// Run `npm run bake:sky` after changing sun.js, skyTokens.js, scatter.js or a moment.
|
||||
// Bakes Midnight Sky and Noonday Sky from src/sky/sun.js into src/sky/baked.ts.
|
||||
// Run `npm run bake:sky` after changing sun.js, skyTokens.js or a moment.
|
||||
import { writeFileSync } from 'node:fs';
|
||||
import { bakeSky } from '../src/sky/skyTokens.js';
|
||||
import { bakeScatter } from '../src/sky/scatter.js';
|
||||
|
||||
const out = new URL('../src/sky/baked.ts', import.meta.url);
|
||||
const baked = {
|
||||
midnight: bakeSky('midnight'),
|
||||
noonday: bakeSky('noonday'),
|
||||
scatter: bakeScatter(),
|
||||
};
|
||||
writeFileSync(
|
||||
out,
|
||||
|
|
|
|||
|
|
@ -1,50 +1,28 @@
|
|||
// The commit a bundle was built from, stamped into its index.html as <meta name="build-sha">, so a built
|
||||
// folder says what it is without a build log: `grep -o 'build-sha" content="[^"]*' dist/index.html`.
|
||||
// Where git governs the tree (REPO_DIR is a repository root) git decides: HEAD, suffixed -dirty when the tree has
|
||||
// uncommitted changes, or `<BUILD_SHA>-mismatch` when an explicit BUILD_SHA names a different commit, so a stamp
|
||||
// never vouches for code it does not hold; a git failure there is 'unknown'. Where git does not govern (a source
|
||||
// archive), a full-sha BUILD_SHA stands, else 'unknown'.
|
||||
import { execFileSync } from 'child_process';
|
||||
import { dirname, resolve } from 'path';
|
||||
import { fileURLToPath } from 'url';
|
||||
|
||||
const REPO_DIR = resolve(dirname(fileURLToPath(import.meta.url)), '..');
|
||||
|
||||
// Vite writes vite.config.js.timestamp-*.mjs next to the config while it loads it; that file is the
|
||||
// build's own, not source, so an UNTRACKED one must not mark the tree dirty. A tracked file of that name,
|
||||
// or any other change, still does. Filtering status lines (not a pathspec) is what keeps it untracked-only.
|
||||
const FULL_SHA = /^[0-9a-f]{40}$/;
|
||||
const VITE_TEMP = /^\?\? (?:.*\/)?vite\.config\.[a-z]+\.timestamp-\d+-[0-9a-f]+\.mjs$/;
|
||||
|
||||
export const gitIn =
|
||||
const gitIn =
|
||||
(cwd) =>
|
||||
(...args) =>
|
||||
execFileSync('git', args, { cwd, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] });
|
||||
|
||||
const FULL_SHA = /^[0-9a-f]{40}$/;
|
||||
|
||||
export const readBuildSha = (env = process.env, run = gitIn(REPO_DIR)) => {
|
||||
const fromEnv = (env.BUILD_SHA ?? '').trim();
|
||||
const explicit = FULL_SHA.test(fromEnv) ? fromEnv : null;
|
||||
// Git governs this tree only when REPO_DIR is its root: a source archive unpacked inside some other
|
||||
// repository has no git of its own, and that repository's HEAD says nothing about it.
|
||||
let governed;
|
||||
try {
|
||||
governed = run('rev-parse', '--show-prefix').trim() === '';
|
||||
} catch {
|
||||
governed = false;
|
||||
}
|
||||
if (!governed) return explicit ?? 'unknown';
|
||||
// Git governs and answers: from here a failure is 'unknown', never the bare explicit sha.
|
||||
const explicit = (env.BUILD_SHA ?? '').trim();
|
||||
const validExplicit = FULL_SHA.test(explicit) ? explicit : null;
|
||||
try {
|
||||
const head = run('rev-parse', 'HEAD').trim();
|
||||
if (!FULL_SHA.test(head)) return 'unknown';
|
||||
if (explicit && explicit !== head) return `${explicit}-mismatch`;
|
||||
if (!FULL_SHA.test(head)) return validExplicit ?? 'unknown';
|
||||
const dirty = run('status', '--porcelain', '-uall', '--', '.')
|
||||
.split('\n')
|
||||
.some((l) => l.trim() !== '' && !VITE_TEMP.test(l));
|
||||
return dirty ? `${head}-dirty` : head;
|
||||
} catch {
|
||||
return 'unknown';
|
||||
return validExplicit ?? 'unknown';
|
||||
}
|
||||
};
|
||||
|
||||
|
|
|
|||
|
|
@ -1,169 +1,27 @@
|
|||
import { execFileSync } from 'child_process';
|
||||
import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from 'fs';
|
||||
import { tmpdir } from 'os';
|
||||
import { join } from 'path';
|
||||
import { afterEach, describe, expect, it } from 'vitest';
|
||||
import { buildShaPlugin, gitIn, readBuildSha } from './buildSha';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { buildShaPlugin, readBuildSha } from './buildSha';
|
||||
|
||||
const SHA = 'b6b1d522f1c0a9d3e2b4c5d6e7f8091a2b3c4d5e';
|
||||
const gitAt =
|
||||
(head, status = '') =>
|
||||
(cmd, ...args) =>
|
||||
cmd === 'rev-parse' ? (args[0] === '--show-prefix' ? '\n' : `${head}\n`) : status;
|
||||
const gitAt = (head, status = '') => (cmd) => cmd === 'rev-parse' ? `${head}\n` : status;
|
||||
|
||||
describe('readBuildSha', () => {
|
||||
it('reads the checkout it is built from', () => {
|
||||
describe('buildSha', () => {
|
||||
it('reads HEAD and marks dirty trees while ignoring vite temp config files', () => {
|
||||
expect(readBuildSha({}, gitAt(SHA))).toBe(SHA);
|
||||
});
|
||||
it('marks a tree with uncommitted changes, so a stamp never vouches for code it does not hold', () => {
|
||||
expect(readBuildSha({}, gitAt(SHA, '?? vite.config.js.timestamp-1-ab.mjs\n'))).toBe(SHA);
|
||||
expect(readBuildSha({}, gitAt(SHA, ' M src/x.ts\n'))).toBe(`${SHA}-dirty`);
|
||||
});
|
||||
it('lets BUILD_SHA stand in where there is no git, and ignores a value that is not a full sha', () => {
|
||||
|
||||
it('falls back to valid BUILD_SHA or unknown when git is absent', () => {
|
||||
const noGit = () => {
|
||||
throw new Error('not a git repository');
|
||||
throw new Error('no git');
|
||||
};
|
||||
expect(readBuildSha({ BUILD_SHA: SHA }, noGit)).toBe(SHA);
|
||||
expect(readBuildSha({ BUILD_SHA: SHA }, gitAt(SHA))).toBe(SHA);
|
||||
// a different HEAD is a mismatch, not a clean stamp of the explicit sha
|
||||
expect(readBuildSha({ BUILD_SHA: SHA }, gitAt('c'.repeat(40)))).toBe(`${SHA}-mismatch`);
|
||||
// a value that is not a lowercase full sha is ignored
|
||||
['b6b1d52', SHA.toUpperCase(), `${SHA}0`].forEach((v) =>
|
||||
expect(readBuildSha({ BUILD_SHA: v }, noGit)).toBe('unknown')
|
||||
);
|
||||
// git that answers but cannot say what the tree holds fails closed
|
||||
const brokenStatus = (cmd, ...args) => {
|
||||
if (cmd === 'status') throw new Error('index file smaller than expected');
|
||||
return args[0] === '--show-prefix' ? '\n' : `${SHA}\n`;
|
||||
};
|
||||
expect(readBuildSha({ BUILD_SHA: SHA }, brokenStatus)).toBe('unknown');
|
||||
expect(readBuildSha({}, brokenStatus)).toBe('unknown');
|
||||
expect(readBuildSha({}, gitAt('nope'))).toBe('unknown');
|
||||
// inside another repository's subfolder git does not govern: the explicit sha stands
|
||||
const nested = (cmd, ...args) => (args[0] === '--show-prefix' ? 'vendor/ratatoskr/\n' : SHA);
|
||||
expect(readBuildSha({ BUILD_SHA: SHA }, nested)).toBe(SHA);
|
||||
expect(readBuildSha({}, nested)).toBe('unknown');
|
||||
expect(readBuildSha({ BUILD_SHA: 'main' }, noGit)).toBe('unknown');
|
||||
expect(readBuildSha({ BUILD_SHA: 'short' }, noGit)).toBe('unknown');
|
||||
expect(readBuildSha({}, noGit)).toBe('unknown');
|
||||
});
|
||||
it("says 'unknown' rather than failing the build when git is absent", () => {
|
||||
expect(
|
||||
readBuildSha({}, () => {
|
||||
throw new Error('spawn git ENOENT');
|
||||
})
|
||||
).toBe('unknown');
|
||||
});
|
||||
});
|
||||
|
||||
describe('readBuildSha against a real repository', () => {
|
||||
const made = [];
|
||||
afterEach(() => {
|
||||
made.splice(0).forEach((d) => rmSync(d, { recursive: true, force: true }));
|
||||
});
|
||||
const repo = () => {
|
||||
const dir = mkdtempSync(join(tmpdir(), 'buildsha-'));
|
||||
made.push(dir);
|
||||
const g = (...a) => execFileSync('git', a, { cwd: dir, stdio: 'ignore' });
|
||||
g('init', '-q');
|
||||
mkdirSync(join(dir, 'src'));
|
||||
writeFileSync(join(dir, 'src', 'a.ts'), 'export {};\n');
|
||||
g('add', '.');
|
||||
g('-c', 'user.name=t', '-c', 'user.email=t@t', 'commit', '-qm', 'x');
|
||||
return dir;
|
||||
};
|
||||
it("stays clean with vite's temp config file present, and is dirty with a stray source file", () => {
|
||||
const dir = repo();
|
||||
const run = gitIn(dir);
|
||||
writeFileSync(join(dir, 'vite.config.js.timestamp-1700000000-abc123.mjs'), '');
|
||||
expect(readBuildSha({}, run)).toMatch(/^[0-9a-f]{40}$/);
|
||||
writeFileSync(join(dir, 'src', 'zz-stray.ts'), '');
|
||||
expect(readBuildSha({}, run)).toMatch(/^[0-9a-f]{40}-dirty$/);
|
||||
});
|
||||
});
|
||||
|
||||
describe('readBuildSha dirty rules against a real repository', () => {
|
||||
const made2 = [];
|
||||
afterEach(() => {
|
||||
made2.splice(0).forEach((d) => rmSync(d, { recursive: true, force: true }));
|
||||
});
|
||||
const TEMP = 'vite.config.js.timestamp-1700000000-abc123.mjs';
|
||||
const repo2 = (tracked = []) => {
|
||||
const dir = mkdtempSync(join(tmpdir(), 'buildsha-'));
|
||||
made2.push(dir);
|
||||
const g = (...a) => execFileSync('git', a, { cwd: dir, stdio: 'ignore' });
|
||||
g('init', '-q');
|
||||
mkdirSync(join(dir, 'src'));
|
||||
writeFileSync(join(dir, 'src', 'a.ts'), 'export {};\n');
|
||||
tracked.forEach((f) => writeFileSync(join(dir, f), 'x\n'));
|
||||
g('add', '.');
|
||||
g('-c', 'user.name=t', '-c', 'user.email=t@t', 'commit', '-qm', 'x');
|
||||
return {
|
||||
dir,
|
||||
head: execFileSync('git', ['rev-parse', 'HEAD'], { cwd: dir, encoding: 'utf8' }).trim(),
|
||||
};
|
||||
};
|
||||
it('does not let an explicit BUILD_SHA mask a dirty tree', () => {
|
||||
const { dir, head } = repo2();
|
||||
const run = gitIn(dir);
|
||||
expect(readBuildSha({ BUILD_SHA: head }, run)).toBe(head);
|
||||
writeFileSync(join(dir, 'src', 'zz-stray.ts'), '');
|
||||
expect(readBuildSha({ BUILD_SHA: head }, run)).toBe(`${head}-dirty`);
|
||||
});
|
||||
it('lets git speak only for a tree whose root it is: an archive unpacked inside another repository keeps its explicit sha', () => {
|
||||
const { dir } = repo2();
|
||||
const inner = join(dir, 'vendor', 'ratatoskr');
|
||||
mkdirSync(inner, { recursive: true });
|
||||
writeFileSync(join(inner, 'x.ts'), '');
|
||||
expect(readBuildSha({ BUILD_SHA: SHA }, gitIn(inner))).toBe(SHA);
|
||||
expect(readBuildSha({}, gitIn(inner))).toBe('unknown');
|
||||
});
|
||||
it("notices an untracked .mjs that is not vite's temp file", () => {
|
||||
const { dir, head } = repo2();
|
||||
writeFileSync(join(dir, 'foo.mjs'), '');
|
||||
expect(readBuildSha({}, gitIn(dir))).toBe(`${head}-dirty`);
|
||||
rmSync(join(dir, 'foo.mjs'));
|
||||
// only vite's exact shape is its own: vite.config.<ext>.timestamp-<digits>-<hex>.mjs
|
||||
[
|
||||
'vite.config.js.timestamp-1-ab.mjs.bak',
|
||||
'vite.config.js.timestamp-x-ab.mjs',
|
||||
'vite.config.js.timestamp-1-zz.mjs',
|
||||
'vite.config.a.b.timestamp-1-ab.mjs',
|
||||
'vite.config.js.timestamp-1-ab-c.mjs',
|
||||
].forEach((name) => {
|
||||
writeFileSync(join(dir, name), '');
|
||||
expect(readBuildSha({}, gitIn(dir)), name).toBe(`${head}-dirty`);
|
||||
rmSync(join(dir, name));
|
||||
});
|
||||
expect(readBuildSha({}, gitIn(dir))).toBe(head);
|
||||
});
|
||||
it('treats a stray source file as dirty even beside the vite temp file, in the root or a subfolder', () => {
|
||||
const { dir, head } = repo2();
|
||||
const run = gitIn(dir);
|
||||
writeFileSync(join(dir, TEMP), '');
|
||||
writeFileSync(join(dir, 'src', TEMP), '');
|
||||
expect(readBuildSha({}, run)).toBe(head);
|
||||
writeFileSync(join(dir, 'src', 'zz-stray.ts'), '');
|
||||
expect(readBuildSha({}, run)).toBe(`${head}-dirty`);
|
||||
});
|
||||
it('marks a tracked file of the temp name dirty once it changes', () => {
|
||||
const { dir, head } = repo2([TEMP]);
|
||||
const run = gitIn(dir);
|
||||
expect(readBuildSha({}, run)).toBe(head);
|
||||
writeFileSync(join(dir, TEMP), 'changed\n');
|
||||
expect(readBuildSha({}, run)).toBe(`${head}-dirty`);
|
||||
});
|
||||
it('marks an untracked file in a new folder dirty (status lists files, not the folder)', () => {
|
||||
const { dir, head } = repo2();
|
||||
mkdirSync(join(dir, 'new'));
|
||||
writeFileSync(join(dir, 'new', TEMP), '');
|
||||
expect(readBuildSha({}, gitIn(dir))).toBe(head);
|
||||
writeFileSync(join(dir, 'new', 'b.ts'), '');
|
||||
expect(readBuildSha({}, gitIn(dir))).toBe(`${head}-dirty`);
|
||||
});
|
||||
});
|
||||
|
||||
describe('buildShaPlugin', () => {
|
||||
it("hands vite a meta tag for the page's head carrying the sha", () => {
|
||||
const plugin = buildShaPlugin(SHA);
|
||||
expect(plugin.transformIndexHtml()).toEqual([
|
||||
it('emits a build-sha meta tag', () => {
|
||||
expect(buildShaPlugin(SHA).transformIndexHtml()).toEqual([
|
||||
{ tag: 'meta', attrs: { name: 'build-sha', content: SHA }, injectTo: 'head-prepend' },
|
||||
]);
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,21 +1,20 @@
|
|||
// Preview builds: set the background scene tier in dist/config.json (default 'low'); config.json
|
||||
// in the repo is the live chat.gamecult.org config (style ridge), and previews pin the style too, ridge unless
|
||||
// given. Previews are static directories with no SPA fallback, so they also switch
|
||||
// in the repo is the live chat.gamecult.org config. Previews are static directories with no SPA fallback, so they also switch
|
||||
// to the hash router: a reload on /login/matrix.org would otherwise be an nginx 404. With --demo it
|
||||
// also switches on the pretend homeserver (src/preview-demo): previewDemo true, and the pretend
|
||||
// server as the only homeserver. Usage:
|
||||
// node scripts/preview-config.js [tier] [style] [--demo]
|
||||
// node scripts/preview-config.js [tier] [--demo]
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
import { fileURLToPath } from 'url';
|
||||
|
||||
const args = process.argv.slice(2);
|
||||
const demo = args.includes('--demo');
|
||||
const [tier = 'low', style = 'ridge'] = args.filter((a) => !a.startsWith('--'));
|
||||
const [tier = 'low'] = args.filter((a) => !a.startsWith('--'));
|
||||
const file = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', 'dist', 'config.json');
|
||||
const config = JSON.parse(fs.readFileSync(file, 'utf8'));
|
||||
config.hashRouter = { enabled: true, basename: '/' };
|
||||
config.backgroundScene = { ...config.backgroundScene, tier, style };
|
||||
config.backgroundScene = { ...config.backgroundScene, tier };
|
||||
if (demo) {
|
||||
config.previewDemo = true;
|
||||
config.defaultHomeserver = 0;
|
||||
|
|
@ -30,5 +29,5 @@ if (demo) {
|
|||
}
|
||||
fs.writeFileSync(file, `${JSON.stringify(config, null, 2)}\n`);
|
||||
console.log(
|
||||
`${file}: backgroundScene.tier = ${tier}, style = ${style}${demo ? ', previewDemo on' : ''}`
|
||||
`${file}: backgroundScene.tier = ${tier}${demo ? ', previewDemo on' : ''}`
|
||||
);
|
||||
|
|
|
|||
|
|
@ -8,9 +8,9 @@ Offline baker for the ridge backdrop: it turns a Copernicus DEM into K+1 G-buffe
|
|||
python3 -I scripts/ridge-bake/export.py <place-id> --tiles DIR --out public/ridge/ [--work DIR] [--sheet contact.png]
|
||||
```
|
||||
|
||||
Needs Python 3 with `numpy`, `tifffile` and `imagecodecs`. `--tiles` is a directory of Copernicus GLO-30 tiles (never committed); `--work` caches the mosaic and rays (default `$TMPDIR/ridge-bake-work`); `--sheet` writes the contact sheet at 1/4 of the ring's width (the ring composite, every card's strip alone and the depth image with every seam, the 32 tile boundaries drawn, lit by one fixed light). The bake prints `r_max_m`, the resident run and the worst fit error per card. `python3 -I scripts/ridge-bake/export.py --write-schema` rewrites `ridge-bake.schema.json`, which the tests pin.
|
||||
Needs Python 3 with `numpy`, `tifffile` and `imagecodecs`. `--tiles` is a directory of Copernicus GLO-30 tiles (never committed); `--work` caches the mosaic and rays (default `$TMPDIR/ridge-bake-work`); `--sheet` writes the contact sheet at 1/4 of the ring's width (the ring composite, every card's strip alone and the depth image with every seam, the 32 tile boundaries drawn, lit by one fixed light). The bake prints `r_max_m`, the resident run and the worst fit error per card.
|
||||
|
||||
Tests: `RIDGE_PY=<python> RIDGE_TILES=DIR scripts/ridge-bake/tests/run.sh [test_ridge.py|mutate.py]` (`mutate.py` re-introduces each rule's failure into a copy of the baker and fails if a test does not notice).
|
||||
Tests: `RIDGE_PY=<python> RIDGE_TILES=DIR scripts/ridge-bake/tests/run.sh`
|
||||
|
||||
## Tiles per preset (`places.json`)
|
||||
|
||||
|
|
|
|||
|
|
@ -1,14 +1,12 @@
|
|||
"""Ridge backdrop export: bake a place with ridge.py and write its K+1 G-buffer cards as 32 azimuth tiles each (colour + geometry WebP per card per tile), a manifest v3 and the index.
|
||||
|
||||
python3 -I scripts/ridge-bake/export.py <place-id> --tiles DIR --out public/ridge/ [--work DIR] [--sheet contact.png]
|
||||
python3 -I scripts/ridge-bake/export.py --write-schema (rewrites ridge-bake.schema.json from SCHEMA below)
|
||||
|
||||
The runtime reads manifest.json (SCHEMA is its contract) and nothing else about the bake. The ring is the whole 360 degrees (ruling ridge-camera-full-ring), absolute compass, column 0 = north, cut into TILES tiles of TILE_W columns plus an APRON of real neighbour
|
||||
The runtime reads manifest.json and nothing else about the bake. The ring is the whole 360 degrees (ruling ridge-camera-full-ring), absolute compass, column 0 = north, cut into TILES tiles of TILE_W columns plus an APRON of real neighbour
|
||||
columns each side; the bake holds no camera: it ships each card tile's distance_m and camera.r_max_m, the largest offset the per-card linear slide can take (ruling ridge-offset-range-fit); the client lights the cards itself (ruling ridge-cards-runtime-lit).
|
||||
The pure parts (budget, bake_id, index, schema check) import no baker; bake_place imports ridge, which needs RIDGE_TILES and RIDGE_WORK (main sets them from --tiles / --work), and so do pack, validate_manifest and write_bake, which read ridge's NEAR_CLIP_M and GROUND_ROWS_MIN."""
|
||||
The pure parts (budget, bake_id, index) import no baker; bake_place imports ridge, which needs RIDGE_TILES and RIDGE_WORK (main sets them from --tiles / --work), and so do pack, validate_manifest and write_bake, which read ridge's NEAR_CLIP_M and GROUND_ROWS_MIN."""
|
||||
import os, sys, json, math, shutil, hashlib, argparse, tempfile
|
||||
from pathlib import Path
|
||||
from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
|
||||
HERE = Path(__file__).resolve().parent
|
||||
sys.path.insert(0, str(HERE))
|
||||
from refusal import Refusal
|
||||
|
|
@ -39,57 +37,14 @@ ATTRIBUTION = dict(
|
|||
dem_source='Copernicus DEM GLO-30 (30 m)',
|
||||
url='https://spacedata.copernicus.eu/collections/copernicus-digital-elevation-model')
|
||||
|
||||
# ------------------------------------------------------------------------------------ schema (the one dict the schema file and the validator both come from)
|
||||
_num, _int, _str = {'type': 'number'}, {'type': 'integer'}, {'type': 'string'}
|
||||
_numnull = {'type': ['number', 'null']}
|
||||
_tz = {'type': 'string', 'format': 'iana-tz'} # an IANA zone the system knows, as ridge.load_preset requires; validate() checks it
|
||||
def _obj(**props): return {'type': 'object', 'required': list(props), 'additionalProperties': False, 'properties': props}
|
||||
def _objnull(**props): return dict(_obj(**props), type=['object', 'null'])
|
||||
_file = _obj(file=_str, bytes=_int)
|
||||
SCHEMA = {'$schema': 'https://json-schema.org/draft/2020-12/schema', 'title': 'ridge-bake manifest v3 and index v1', '$defs': {
|
||||
'manifest': _obj(schema={'const': 3}, baker_version=_int, bake_id=_str,
|
||||
place=_obj(id=_str, name=_str, lat=_num, lon=_num, altitude_km=_num, eye_m=_num, tz=_tz),
|
||||
view=_obj(look_az_deg=_num, ring_w={'const': RING_W}, tile_w={'const': TILE_W}, tiles={'const': TILES}, apron={'const': APRON}, plane_h=_int, px_per_deg_h=_num, px_per_deg_v=_num, exaggeration=_num, horizon_row=_num, sky_row=_num, near_row=_num),
|
||||
curvature=_obj(r_earth_m=_num, k_ref=_num),
|
||||
encoding=_obj(log_d_min=_num, log_d_max=_num, normal={'const': 'rt8'}),
|
||||
camera=dict(_obj(r_max_m=_num, r_max_forward_m=_num), description="r_max_m (every camera angle on its circle) and r_max_forward_m (the camera on its heading) are the offsets up to which the linear slide holds (the fit error at most FIT_PX_MAX card px) for the NEAREST solid terrain (at or beyond the near clip, ridge.NEAR_CLIP_M, 500 m) that each card draws in each tile, not for the tile's median distance_m; a tile whose card 0 draws only near ground (under the clip) is slid at the clip distance (its distance_m) and binds at 500 m. The ground under the clip is drawn by card 0 from the near march and is otherwise not measured."),
|
||||
cards={'type': 'array', 'minItems': 1, 'maxItems': MAX_CARDS, 'items': _obj(near_m=_numnull, far_m=_numnull),
|
||||
'description': "nearest first; the runtime paints the list last to first. near_m and far_m are the median seam depths over the ring, null at the ends."},
|
||||
tiles={'type': 'array', 'minItems': TILES, 'maxItems': TILES, 'items': {'type': 'array', 'minItems': 1, 'maxItems': MAX_CARDS, 'items': _objnull(top=_int, h=_int, distance_m=_num, colour=_file, geometry=_file)},
|
||||
'description': "tiles[t][i] is card i in tile t, or null where the card holds nothing in that tile (the client takes its distance from the neighbouring tiles). Tile t owns the ring columns [tile_w t, tile_w (t + 1)), column c at azimuth (c + 0.5) / ring_w x 360, 0 = north; its files hold [tile_w t - apron, tile_w (t + 1) + apron), wrapping at the ring's end, and are tile_w + 2 apron columns wide. top and h place the card's band back at its rows of the frame; distance_m = exp(median ln d) of the card's solid pixels in the tile that are neither wall nor near ground, under the near clip (the interior tile_w columns); a tile whose card draws only near ground gets the clip distance."},
|
||||
bytes=_int,
|
||||
attribution=_obj(credit_line=_str, licence=_str, dem_source=_str, url=_str)),
|
||||
'index': _obj(schema={'const': 1}, default=_str, places={'type': 'object', 'additionalProperties': _str})}}
|
||||
def tile_file(i, t, kind): return f'card-{i}-t{t:02d}-{kind}.webp'
|
||||
|
||||
def validate(x, s, path='$'):
|
||||
"""The subset of JSON Schema SCHEMA uses; raises Refusal naming the path."""
|
||||
if '$ref' in s: return validate(x, SCHEMA['$defs'][s['$ref'].split('/')[-1]], path)
|
||||
tys = s.get('type'); tys = [tys] if isinstance(tys, str) else tys; py = {'object': dict, 'array': list, 'string': str, 'number': (int, float), 'integer': int, 'null': type(None)}
|
||||
if tys and not any(isinstance(x, py[t]) and not (isinstance(x, bool) and t != 'null') for t in tys): raise Refusal(f'{path}: not a {"/".join(tys)}')
|
||||
if s.get('format') == 'iana-tz':
|
||||
try: ZoneInfo(x)
|
||||
except (ZoneInfoNotFoundError, ValueError, OSError): raise Refusal(f'{path}: {x!r} is not a time zone the system knows')
|
||||
if 'const' in s and x != s['const']: raise Refusal(f"{path}: must be {s['const']!r}")
|
||||
if 'enum' in s and x not in s['enum']: raise Refusal(f'{path}: not one of {s["enum"]}')
|
||||
if 'maximum' in s and x > s['maximum']: raise Refusal(f'{path}: above {s["maximum"]}')
|
||||
if isinstance(x, list):
|
||||
if not s.get('minItems', 0) <= len(x) <= s.get('maxItems', 1 << 30): raise Refusal(f'{path}: wrong length')
|
||||
for i, v in enumerate(x): validate(v, s['items'], f'{path}[{i}]')
|
||||
if isinstance(x, dict):
|
||||
props = s.get('properties', {}); extra = s.get('additionalProperties', True)
|
||||
for k in s.get('required', []):
|
||||
if k not in x: raise Refusal(f'{path}: missing {k}')
|
||||
for k, v in x.items():
|
||||
if k in props: validate(v, props[k], f'{path}.{k}')
|
||||
elif extra is False: raise Refusal(f'{path}: extra key {k}')
|
||||
elif isinstance(extra, dict): validate(v, extra, f'{path}.{k}')
|
||||
|
||||
def validate_manifest(m):
|
||||
"""The schema plus what it cannot say: the plane keeps ridge.GROUND_ROWS_MIN rows under the horizon, every tile lists one entry per card, every card holds something in some tile, each file is named for its card and tile, bytes is the sum of the files."""
|
||||
"""Check the baked manifest's structural invariants: the plane keeps ridge.GROUND_ROWS_MIN rows under the horizon, there are TILES tiles of one entry per card, every card holds something in some tile, each file is named for its card and tile, bytes is the sum of the files."""
|
||||
import ridge
|
||||
validate(m, SCHEMA['$defs']['manifest']); k = len(m['cards']); v = m['view']
|
||||
k = len(m['cards']); v = m['view']
|
||||
if v['plane_h'] - v['horizon_row'] < ridge.GROUND_ROWS_MIN - 1e-6: raise Refusal(f"$.view: {v['plane_h'] - v['horizon_row']:.1f} rows under the horizon, below the {ridge.GROUND_ROWS_MIN} the runtime needs (ridge.GROUND_ROWS_MIN)")
|
||||
if len(m['tiles']) != TILES: raise Refusal(f"$.tiles: {len(m['tiles'])} tiles, expected {TILES}")
|
||||
for t, row in enumerate(m['tiles']):
|
||||
if len(row) != k: raise Refusal(f'$.tiles[{t}]: {len(row)} entries for {k} cards')
|
||||
for i, e in enumerate(row):
|
||||
|
|
@ -226,7 +181,6 @@ def write_bake(out, place, view, meta, packed, opaque, default=None):
|
|||
(tmp / 'manifest.json').write_bytes(text.encode('utf-8')) # bytes, so the platform's newline cannot move the file under its id
|
||||
idx_path = out / 'index.json'; idx = json.loads(idx_path.read_text()) if idx_path.exists() else dict(schema=1, default=place['id'], places={})
|
||||
old = idx['places'].get(place['id']); idx['places'][place['id']] = name; idx['default'] = default or (idx['default'] if idx['default'] in idx['places'] else place['id'])
|
||||
validate(idx, SCHEMA['$defs']['index'])
|
||||
if dest.exists(): shutil.rmtree(dest)
|
||||
os.rename(tmp, dest); (out / '.index.tmp').write_bytes((json.dumps(idx, indent=1) + '\n').encode('utf-8')); os.replace(out / '.index.tmp', idx_path)
|
||||
if old and old != name: shutil.rmtree(out / old, ignore_errors=True)
|
||||
|
|
@ -300,10 +254,8 @@ def sheet(bake):
|
|||
return bytes(imagecodecs.png_encode(u8(np.concatenate([bounds(q(comp))] + [bounds(q(p)) for p in panels] + [bounds(depth)], 0))))
|
||||
|
||||
def main(argv=None):
|
||||
ap = argparse.ArgumentParser(description=__doc__.split('\n')[0]); ap.add_argument('place', nargs='?'); ap.add_argument('--tiles'); ap.add_argument('--out'); ap.add_argument('--work'); ap.add_argument('--sheet'); ap.add_argument('--write-schema', action='store_true')
|
||||
ap = argparse.ArgumentParser(description=__doc__.split('\n')[0]); ap.add_argument('place'); ap.add_argument('--tiles', required=True); ap.add_argument('--out', required=True); ap.add_argument('--work'); ap.add_argument('--sheet')
|
||||
a = ap.parse_args(argv)
|
||||
if a.write_schema: (HERE / 'ridge-bake.schema.json').write_bytes((json.dumps(SCHEMA, indent=1, ensure_ascii=False) + '\n').encode('utf-8')); return 0
|
||||
if not (a.place and a.tiles and a.out): ap.error('place, --tiles and --out are required')
|
||||
os.environ['RIDGE_TILES'] = a.tiles; os.environ['RIDGE_WORK'] = a.work or os.path.join(os.environ.get('TMPDIR', tempfile.gettempdir()), 'ridge-bake-work'); os.makedirs(os.environ['RIDGE_WORK'], exist_ok=True)
|
||||
bake = bake_place(a.place)
|
||||
if a.sheet: Path(a.sheet).write_bytes(sheet(bake))
|
||||
|
|
|
|||
|
|
@ -1,2 +1,2 @@
|
|||
"""The baker's refusal: raised wherever ridge.py or export.py declines a preset, a view or a bake. The fixtures catch this class only, so an exception from numpy or the standard library reaching them is a crash (mutate.py: CRASHED), never a kill."""
|
||||
"""The baker's refusal: raised wherever ridge.py or export.py declines a preset, a view or a bake."""
|
||||
class Refusal(ValueError): pass
|
||||
|
|
|
|||
|
|
@ -1,327 +0,0 @@
|
|||
{
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"title": "ridge-bake manifest v3 and index v1",
|
||||
"$defs": {
|
||||
"manifest": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"schema",
|
||||
"baker_version",
|
||||
"bake_id",
|
||||
"place",
|
||||
"view",
|
||||
"curvature",
|
||||
"encoding",
|
||||
"camera",
|
||||
"cards",
|
||||
"tiles",
|
||||
"bytes",
|
||||
"attribution"
|
||||
],
|
||||
"additionalProperties": false,
|
||||
"properties": {
|
||||
"schema": {
|
||||
"const": 3
|
||||
},
|
||||
"baker_version": {
|
||||
"type": "integer"
|
||||
},
|
||||
"bake_id": {
|
||||
"type": "string"
|
||||
},
|
||||
"place": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"id",
|
||||
"name",
|
||||
"lat",
|
||||
"lon",
|
||||
"altitude_km",
|
||||
"eye_m",
|
||||
"tz"
|
||||
],
|
||||
"additionalProperties": false,
|
||||
"properties": {
|
||||
"id": {
|
||||
"type": "string"
|
||||
},
|
||||
"name": {
|
||||
"type": "string"
|
||||
},
|
||||
"lat": {
|
||||
"type": "number"
|
||||
},
|
||||
"lon": {
|
||||
"type": "number"
|
||||
},
|
||||
"altitude_km": {
|
||||
"type": "number"
|
||||
},
|
||||
"eye_m": {
|
||||
"type": "number"
|
||||
},
|
||||
"tz": {
|
||||
"type": "string",
|
||||
"format": "iana-tz"
|
||||
}
|
||||
}
|
||||
},
|
||||
"view": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"look_az_deg",
|
||||
"ring_w",
|
||||
"tile_w",
|
||||
"tiles",
|
||||
"apron",
|
||||
"plane_h",
|
||||
"px_per_deg_h",
|
||||
"px_per_deg_v",
|
||||
"exaggeration",
|
||||
"horizon_row",
|
||||
"sky_row",
|
||||
"near_row"
|
||||
],
|
||||
"additionalProperties": false,
|
||||
"properties": {
|
||||
"look_az_deg": {
|
||||
"type": "number"
|
||||
},
|
||||
"ring_w": {
|
||||
"const": 6400
|
||||
},
|
||||
"tile_w": {
|
||||
"const": 200
|
||||
},
|
||||
"tiles": {
|
||||
"const": 32
|
||||
},
|
||||
"apron": {
|
||||
"const": 2
|
||||
},
|
||||
"plane_h": {
|
||||
"type": "integer"
|
||||
},
|
||||
"px_per_deg_h": {
|
||||
"type": "number"
|
||||
},
|
||||
"px_per_deg_v": {
|
||||
"type": "number"
|
||||
},
|
||||
"exaggeration": {
|
||||
"type": "number"
|
||||
},
|
||||
"horizon_row": {
|
||||
"type": "number"
|
||||
},
|
||||
"sky_row": {
|
||||
"type": "number"
|
||||
},
|
||||
"near_row": {
|
||||
"type": "number"
|
||||
}
|
||||
}
|
||||
},
|
||||
"curvature": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"r_earth_m",
|
||||
"k_ref"
|
||||
],
|
||||
"additionalProperties": false,
|
||||
"properties": {
|
||||
"r_earth_m": {
|
||||
"type": "number"
|
||||
},
|
||||
"k_ref": {
|
||||
"type": "number"
|
||||
}
|
||||
}
|
||||
},
|
||||
"encoding": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"log_d_min",
|
||||
"log_d_max",
|
||||
"normal"
|
||||
],
|
||||
"additionalProperties": false,
|
||||
"properties": {
|
||||
"log_d_min": {
|
||||
"type": "number"
|
||||
},
|
||||
"log_d_max": {
|
||||
"type": "number"
|
||||
},
|
||||
"normal": {
|
||||
"const": "rt8"
|
||||
}
|
||||
}
|
||||
},
|
||||
"camera": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"r_max_m",
|
||||
"r_max_forward_m"
|
||||
],
|
||||
"additionalProperties": false,
|
||||
"properties": {
|
||||
"r_max_m": {
|
||||
"type": "number"
|
||||
},
|
||||
"r_max_forward_m": {
|
||||
"type": "number"
|
||||
}
|
||||
},
|
||||
"description": "r_max_m (every camera angle on its circle) and r_max_forward_m (the camera on its heading) are the offsets up to which the linear slide holds (the fit error at most FIT_PX_MAX card px) for the NEAREST solid terrain (at or beyond the near clip, ridge.NEAR_CLIP_M, 500 m) that each card draws in each tile, not for the tile's median distance_m; a tile whose card 0 draws only near ground (under the clip) is slid at the clip distance (its distance_m) and binds at 500 m. The ground under the clip is drawn by card 0 from the near march and is otherwise not measured."
|
||||
},
|
||||
"cards": {
|
||||
"type": "array",
|
||||
"minItems": 1,
|
||||
"maxItems": 6,
|
||||
"items": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"near_m",
|
||||
"far_m"
|
||||
],
|
||||
"additionalProperties": false,
|
||||
"properties": {
|
||||
"near_m": {
|
||||
"type": [
|
||||
"number",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"far_m": {
|
||||
"type": [
|
||||
"number",
|
||||
"null"
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
"description": "nearest first; the runtime paints the list last to first. near_m and far_m are the median seam depths over the ring, null at the ends."
|
||||
},
|
||||
"tiles": {
|
||||
"type": "array",
|
||||
"minItems": 32,
|
||||
"maxItems": 32,
|
||||
"items": {
|
||||
"type": "array",
|
||||
"minItems": 1,
|
||||
"maxItems": 6,
|
||||
"items": {
|
||||
"type": [
|
||||
"object",
|
||||
"null"
|
||||
],
|
||||
"required": [
|
||||
"top",
|
||||
"h",
|
||||
"distance_m",
|
||||
"colour",
|
||||
"geometry"
|
||||
],
|
||||
"additionalProperties": false,
|
||||
"properties": {
|
||||
"top": {
|
||||
"type": "integer"
|
||||
},
|
||||
"h": {
|
||||
"type": "integer"
|
||||
},
|
||||
"distance_m": {
|
||||
"type": "number"
|
||||
},
|
||||
"colour": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"file",
|
||||
"bytes"
|
||||
],
|
||||
"additionalProperties": false,
|
||||
"properties": {
|
||||
"file": {
|
||||
"type": "string"
|
||||
},
|
||||
"bytes": {
|
||||
"type": "integer"
|
||||
}
|
||||
}
|
||||
},
|
||||
"geometry": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"file",
|
||||
"bytes"
|
||||
],
|
||||
"additionalProperties": false,
|
||||
"properties": {
|
||||
"file": {
|
||||
"type": "string"
|
||||
},
|
||||
"bytes": {
|
||||
"type": "integer"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"description": "tiles[t][i] is card i in tile t, or null where the card holds nothing in that tile (the client takes its distance from the neighbouring tiles). Tile t owns the ring columns [tile_w t, tile_w (t + 1)), column c at azimuth (c + 0.5) / ring_w x 360, 0 = north; its files hold [tile_w t - apron, tile_w (t + 1) + apron), wrapping at the ring's end, and are tile_w + 2 apron columns wide. top and h place the card's band back at its rows of the frame; distance_m = exp(median ln d) of the card's solid pixels in the tile that are neither wall nor near ground, under the near clip (the interior tile_w columns); a tile whose card draws only near ground gets the clip distance."
|
||||
},
|
||||
"bytes": {
|
||||
"type": "integer"
|
||||
},
|
||||
"attribution": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"credit_line",
|
||||
"licence",
|
||||
"dem_source",
|
||||
"url"
|
||||
],
|
||||
"additionalProperties": false,
|
||||
"properties": {
|
||||
"credit_line": {
|
||||
"type": "string"
|
||||
},
|
||||
"licence": {
|
||||
"type": "string"
|
||||
},
|
||||
"dem_source": {
|
||||
"type": "string"
|
||||
},
|
||||
"url": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"index": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"schema",
|
||||
"default",
|
||||
"places"
|
||||
],
|
||||
"additionalProperties": false,
|
||||
"properties": {
|
||||
"schema": {
|
||||
"const": 1
|
||||
},
|
||||
"default": {
|
||||
"type": "string"
|
||||
},
|
||||
"places": {
|
||||
"type": "object",
|
||||
"additionalProperties": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,130 +0,0 @@
|
|||
"""Mutation check: re-introduce a cause into a COPY of the baker, run the fixtures against it, and require that at least one fails.
|
||||
venv/bin/python tests/mutate.py [word ...] (runs the unmutated copy first and exits 2 if a fixture fails; prints one line per mutant whose name holds every word; exit 1 if a mutant survives or only crashes the run: a kill is an AssertionError raised by the fixtures' own code)"""
|
||||
import os, shutil, subprocess, sys, tempfile
|
||||
HERE = os.path.dirname(os.path.abspath(__file__)); SRC = os.path.join(HERE, '..')
|
||||
MUTANTS = { # name -> (text in ridge.py or export.py, replacement)
|
||||
'seam cost: the rows a seam sweeps are not paid (it hops across a receding ridge)': ("np.cumsum(0.5 * (cov[:, x - 1] + cov[:, x])) + SEAM_LAM * bins", "SEAM_LAM * bins"),
|
||||
'seam prior pulls hard to the target (2.0, or 0.1: the seam hops across a ridge)': ("SEAM_PRIOR = 0.02 ", "SEAM_PRIOR = 2.0 "),
|
||||
'normals: the authored exaggeration is dropped': ("h = np.asarray(h, np.float64); E = PXDEG_V / HPX_DEG", "h = np.asarray(h, np.float64); E = 1.0"),
|
||||
'normals: the lateral neighbour is one sample nearer (not equal distance)': ("st = E * (np.roll(h, -1, axis=1) - np.roll(h, 1, axis=1))", "st = E * (np.roll(np.roll(h, -1, axis=1), 1, axis=0) - np.roll(h, 1, axis=1))"),
|
||||
'cards: the near edge is ignored (every card starts at sample 0)': ("k0 = 0 if i == 0 else int(ks0[i - 1][x])", "k0 = 0"),
|
||||
'cards: the farther card fades in over the window too (both cards translucent)': ("X[i, :, x] = 1 - s * s * (3 - 2 * s)", "X[i, :, x] = 1 - s * s * (3 - 2 * s); X[i + 1, :, x] = s * s * (3 - 2 * s)"),
|
||||
'cards: a crest row is all or nothing (no fractional coverage)': ("F[i, :, x] = np.where(hit, np.clip((rm[-1] - lo) / p, 0, 1), 0)", "F[i, :, x] = np.where(hit, 1.0, 0)"),
|
||||
'prefilter ignores sigma': ("if sigma_m > 0:", "if False:"),
|
||||
'prefilter across rays uses one sigma in columns (not per distance)': ("sc = sigma_m / (d * COLW)", "sc = sigma_m / (d[0] * COLW) * np.ones_like(d)"),
|
||||
'bake_id hashes geometry before colour': ("h.update(colour); h.update(geometry)", "h.update(geometry); h.update(colour)"),
|
||||
'check_cover accepts any composite': ("if bad.any(): y, x", "if False: y, x"),
|
||||
'load_preset accepts splits that do not increase': ("or any(b <= a for a, b in zip(sp, sp[1:]))", ""),
|
||||
'geometry: n_r and n_t channels swapped': ("r, t = u8((np.asarray(n_r) + 1) / 2), u8((np.asarray(n_t) + 1) / 2)", "r, t = u8((np.asarray(n_t) + 1) / 2), u8((np.asarray(n_r) + 1) / 2)"),
|
||||
'geometry: log-distance not normalised by the encoding range': ("b = (np.asarray(logd) - enc['log_d_min']) / (enc['log_d_max'] - enc['log_d_min'])", "b = np.asarray(logd) / 12.0"),
|
||||
'colour: albedo zeroed in the file': ("rgb = u8(albedo) * (a[..., None] > 0)", "rgb = u8(albedo) * 0"),
|
||||
'colour: premultiplied instead of straight': ("rgb = u8(albedo) * (a[..., None] > 0)", "rgb = u8(np.asarray(albedo) * np.asarray(alpha)[..., None])"),
|
||||
'seams: the separation between seams is ignored': ("SEAM_SEP = 0.4 ", "SEAM_SEP = 0.0 "),
|
||||
'elev: curvature and refraction dropped': ("drop = d * d / (2 * R_EARTH) * (1 - KREF) if curvature else 0.0", "drop = 0.0"),
|
||||
'coverage: the rows below the first sample are not counted': ("prev = np.vstack([np.full((1, a.shape[1]), BOTTOM_DEG), runmax[:-1]])", "prev = np.vstack([np.full((1, a.shape[1]), 100.0), runmax[:-1]])"),
|
||||
'coverage: the rows below the first sample are counted twice': ("* PXDEG_V)\n return C", "* PXDEG_V); C[0] += np.clip(np.minimum(a[0], TOP_DEG) - BOTTOM_DEG, 0, None) * PXDEG_V\n return C"),
|
||||
'cards: the hit is not interpolated between samples': ("t = np.where(idx > 0, np.clip((rowang - prev) / np.maximum(rm[idx] - prev, 1e-9), 0, 1), 1.0)", "t = np.ones_like(rowang)"),
|
||||
'cards: the blended normal is not renormalised': ("nz = np.sqrt(g[2] ** 2 + g[3] ** 2 + g[4] ** 2) + 1e-12", "nz = 1.0"),
|
||||
'wall: no row is flagged (the flag is dropped)': ("Wl[i, :, x] = hit & (idx == 0)", "Wl[i, :, x] = False"),
|
||||
'near: the cap to the silhouette of the terrain at the clip is dropped': ("an = np.minimum(an, a[0][None, :])", "an = an"),
|
||||
'near: rows under the clip are flagged wall': ("Wl[i, :, x] = hit & (idx == 0); Nr[i, :, x] = hit & (kp < kn)", "Wl[i, :, x] = hit & ((idx == 0) | (kp < kn)); Nr[i, :, x] = hit & (kp < kn)"),
|
||||
'near: albedo takes the face up (the wall rule on near rows)': ("albedo(g[1], np.where(Wl[i, sl], 1.0, g[4] / nz), material)", "albedo(g[1], np.where(Wl[i, sl] | Nr[i, sl], 1.0, g[4] / nz), material)"),
|
||||
'near: albedo reads the height of the far march first sample': ("albedo(g[1], np.where(Wl[i, sl]", "albedo(np.where(Nr[i, sl], h[int(np.searchsorted(d, NEAR_CLIP_M))][None, :], g[1]), np.where(Wl[i, sl]"),
|
||||
'near: the march starts at 20 m': ("NEAR_START_M = 1.0 ", "NEAR_START_M = 20.0 "),
|
||||
'near: the heights are stored float32': (", np.float64) for dk in d])", ", np.float32) for dk in d])"),
|
||||
'near: the place prefilter is not applied': ("; a, h = prefilter(d, h, sigma_m)\n", "; a, h = prefilter(d, h, 0.0)\n"),
|
||||
'near: the far normals are computed over the joined march (not apart)': ("nn, nf = normals(dn, hn), normals(d, h)", "nj_ = normals(np.concatenate([dn, d]), np.concatenate([hn, h])); nn, nf = tuple(x[:len(dn)] for x in nj_), tuple(x[len(dn):] for x in nj_)"),
|
||||
'near: cards accepts a march that starts at the clip': ("if d[0] >= NEAR_CLIP_M: raise Refusal", "if False: raise Refusal"),
|
||||
'pack: near pixels count as solid terrain': ("solid = (al >= 0.5) & ~wl & ~nr;", "solid = (al >= 0.5) & ~wl;"),
|
||||
'pack: the non-wall fallback pool reads near pixels': ("((al > 0) & ~wl & ~nr, ld)", "((al > 0) & ~wl, ld)"),
|
||||
'pack: the lit fallback pool reads near pixels': ("((al > 0) & ~nr, ld)", "(al > 0, ld)"),
|
||||
'pack: the apron fallback pool reads near pixels': ("((c['alpha'] > 0) & ~c['near'], c['logd'])", "(c['alpha'] > 0, c['logd'])"),
|
||||
'pack: a tile with nothing outside the near ground is not at the clip': ("if pool else ridge.NEAR_CLIP_M", "if pool else 0.0"),
|
||||
'r_max: the tile median binds, not the nearest terrain': ("r_max = solve_r_max(near, bands, ppd); r_fwd = solve_r_max(near, bands, ppd, phis=1)", "r_max = solve_r_max(dist, bands, ppd); r_fwd = solve_r_max(dist, bands, ppd, phis=1)"),
|
||||
'r_max: near pixels do not bind at the clip': ("ridge.NEAR_CLIP_M if ((al >= 0.5) & nr).any() else None", "None"),
|
||||
'r_max: near pixels bind only in a tile with no other solid pixel': ("ridge.NEAR_CLIP_M if ((al >= 0.5) & nr).any() else None", "ridge.NEAR_CLIP_M if ((al >= 0.5) & nr).any() and not solid.any() else None"),
|
||||
'r_max: near pixels bind only where they outnumber the solid ones': ("ridge.NEAR_CLIP_M if ((al >= 0.5) & nr).any() else None", "ridge.NEAR_CLIP_M if ((al >= 0.5) & nr).sum() > solid.sum() else None"),
|
||||
'r_max: the nearest pixel is the farthest solid one': ("float(np.exp(ld[solid].min())) if solid.any() else None, ridge", "float(np.exp(ld[solid].max())) if solid.any() else None, ridge"),
|
||||
'near clip: the writer compares the float32 distance strictly': ("if rmin < ridge.NEAR_CLIP_M * (1 - 1e-5): raise", "if rmin < ridge.NEAR_CLIP_M: raise"),
|
||||
'near clip: the march starts nearer than the clip': ("d = [NEAR_CLIP_M]", "d = [100.0]"),
|
||||
'near clip: a card 0 inside the clip is accepted by the writer': ("if rmin < ridge.NEAR_CLIP_M * (1 - 1e-5): raise", "if False: raise"),
|
||||
'view: the 1x floor is back': ("lo, hi = E_MIN * HPX_DEG, 10 * HPX_DEG", "lo, hi = HPX_DEG, 10 * HPX_DEG"),
|
||||
'view: the horizon anchor is dropped (the scale is the skyline fit alone)': ("ppd = float(np.clip(min(fit, hold), lo, hi))", "ppd = float(np.clip(fit, lo, hi))"),
|
||||
'view: a skyline that cannot hold the ground rows is not refused': ("if hold < lo: raise", "if False: raise"),
|
||||
'view: the ground rows are not asked for (GROUND_ROWS_MIN 0)': ("GROUND_ROWS_MIN = 150 ", "GROUND_ROWS_MIN = 0 "),
|
||||
'validate_manifest: a plane short of its ground rows is accepted': ("if v['plane_h'] - v['horizon_row'] < ridge.GROUND_ROWS_MIN - 1e-6: raise", "if False: raise"),
|
||||
'wall: albedo takes the face normal, not the face up': ("np.where(Wl[i, sl], 1.0, g[4] / nz)", "g[4] / nz"),
|
||||
'wall: the code is not written to the geometry': ("if wall is not None: m = np.asarray(wall, bool)", "if False: m = np.asarray(wall, bool)"),
|
||||
'wall: the sheet lights wall rows with their normal': ("wall = c['wall']; n_r, n_t = np.where(wall, 0.0, c['n_r']), np.where(wall, 0.0, c['n_t'])", "n_r, n_t = c['n_r'], c['n_t']"),
|
||||
'ring: the seam DP is not periodic (the first lap is kept, not the middle)': ("return out[:, n:2 * n]", "return out[:, :n]"),
|
||||
'ring: the tile take does not wrap (the ring ends repeat their edge column)': ("return np.take(a, (c0 + np.arange(n)) % W, axis=-1)", "return np.take(a, np.clip(c0 + np.arange(n), 0, W - 1), axis=-1)"),
|
||||
'tile: the apron is shifted (a tile starts at its own first column)': ("ridge.ring_cols(x, t * TILE_W - APRON, TILE_W + 2 * APRON)", "ridge.ring_cols(x, t * TILE_W, TILE_W + 2 * APRON)"),
|
||||
'tile: the seams are cut from tile 0 for every tile': ("cols(sm, t), tuple(cols(x, t) for x in nrm)", "cols(sm, 0), tuple(cols(x, t) for x in nrm)"),
|
||||
'view: the vertical anchors read the first 72 degrees only (the old window)': ("sk = np.asarray(skyline); sky", "sk = np.asarray(skyline)[:1280]; sky"),
|
||||
'bake_id: card-major instead of tile-major': ("bake_id(text, [(e['colour'], e['geometry']) for row in tiles for e in row if e])", "bake_id(text, [(row[i]['colour'], row[i]['geometry']) for i in range(k) for row in tiles if row[i]])"),
|
||||
'bake_id: the manifest is not hashed (a manifest moves under its id)': ("h = hashlib.sha256(); h.update(manifest_text.encode('utf-8'))", "h = hashlib.sha256()"),
|
||||
'bake_id: the manifest is hashed with the id already in it (the blank is skipped)': ("bid = bake_id(text, [", "bid = bake_id(text.replace(BAKE_ID_BLANK, '111111111111'), ["),
|
||||
'write: the per-tile cover check is dropped': ("except Refusal as ex: raise Refusal(f'tile {t}: {ex}')", "except Refusal as ex: pass"),
|
||||
'write: the apron width is not checked': ("if c.shape[1] != w: raise", "if False: raise"),
|
||||
'budget: the tile cap is ignored': ("if b > TILE_BYTES_MAX: raise", "if False: raise"),
|
||||
'budget: the place cap is ignored': ("if sum(tile_bytes) > PLACE_BYTES_MAX: raise", "if False: raise"),
|
||||
'budget: the resident gate is ignored': ("if res > RESIDENT_BYTES_MAX: raise", "if False: raise"),
|
||||
'budget: the resident run does not wrap the ring': ("sum(per[(t + k) % TILES] for k in range(n))", "sum(per[t + k] for k in range(n) if t + k < TILES)"),
|
||||
'budget: the run length forgets the margin tiles': ("math.ceil(arc / TILE_DEG) + 1 + 4", "math.ceil(arc / TILE_DEG)"),
|
||||
'r_max: the camera sweeps forward only (phi = 0)': ("PHI_STEPS = 24 ", "PHI_STEPS = 1 "),
|
||||
'r_max: every card of a tile is fitted at the nearest card distance': ("fit_px(d, r, px_per_deg, phis) for d in row", "fit_px(row[0] if row[0] is not None else d, r, px_per_deg, phis) for d in row"),
|
||||
'r_max_forward: the forward offset is searched over the whole circle': ("r_fwd = solve_r_max(near, bands, ppd, phis=1)", "r_fwd = solve_r_max(near, bands, ppd)"),
|
||||
'r_max_forward: the resident gate is not checked at the forward offset': ("for r in (camera['r_max_m'], camera['r_max_forward_m']): check_budget", "for r in (camera['r_max_m'],): check_budget"),
|
||||
'r_max_forward: a forward offset below r_max_m is accepted': ("if camera['r_max_forward_m'] < camera['r_max_m']: raise", "if False: raise"),
|
||||
'fit: the line is the least squares of 33 uniform samples, as the first gate drew it': ("x, w = np.polynomial.legendre.leggauss(FIT_QUAD)", "x = np.linspace(-1, 1, 33); w = np.full(33, 2 / 33)"),
|
||||
'fit: the line is a two-node quadrature': ("FIT_QUAD = 48 ", "FIT_QUAD = 2 "),
|
||||
'write: the manifest is written as platform text (CRLF on Windows)': ("(tmp / 'manifest.json').write_bytes(text.encode('utf-8'))", "(tmp / 'manifest.json').write_text(text)"),
|
||||
'write: the index is written as platform text (CRLF on Windows)': ("(out / '.index.tmp').write_bytes((json.dumps(idx, indent=1) + '\\n').encode('utf-8'))", "(out / '.index.tmp').write_text(json.dumps(idx, indent=1) + '\\n')"),
|
||||
'r_max: not capped at half the nearest distance': ("cap = 0.5 * rmin", "cap = 5.0 * rmin"),
|
||||
'r_max: the resident gate is not part of the search': (" and resident_bytes(bands, run_tiles(r, rmin)) <= RESIDENT_BYTES_MAX\n", "\n"),
|
||||
'r_max: a bake below the floor is accepted': ("if r_max < R_MAX_FLOOR_M:", "if False:"),
|
||||
'pack: the distance counts wall rows': ("solid = (al >= 0.5) & ~wl & ~nr; any_solid", "solid = (al >= 0.5) & ~nr; any_solid"),
|
||||
'pack: the distance reads the apron columns too': ("inner = slice(APRON, APRON + TILE_W)", "inner = slice(0, TILE_W + 2 * APRON)"),
|
||||
'sheet: the tile boundaries are not drawn': ("def bounds(img): img[:, mark] = 0.45 * img[:, mark] + 0.55 * red; return img", "def bounds(img): return img"),
|
||||
'export: an empty card is not refused': ("if all(tile[i]['alpha'].shape[0] == 0 for tile in bake['cards']): raise", "if False: raise"),
|
||||
'material: a null steep override still paints steep faces rock grey (strata do not hold on cliffs)': ("if material['steep']: c = c + (np.asarray(material['steep']['colour'])", "if True: c = c + (np.asarray((material['steep'] or dict(colour=[0.47, 0.44, 0.41]))['colour'])"),
|
||||
'material: the ramps apply in reverse order': ("for r in material['ramps']:", "for r in reversed(material['ramps']):"),
|
||||
'material: a null snow still snows': ("sn = material['snow']", "sn = material['snow'] or dict(from_m=1900, to_m=2300, colour=[0.93, 0.95, 0.97])"),
|
||||
'material: an unknown name falls back to alpine': ("if name not in tab: raise Refusal(", "if name not in tab: name = 'alpine'; ("),
|
||||
'material: the cards take the alpine colours whatever the place names': ("ridge.cards(D, cols(A, t), cols(Hc, t), cols(sm, t), tuple(cols(x, t) for x in nrm), material=material)", "ridge.cards(D, cols(A, t), cols(Hc, t), cols(sm, t), tuple(cols(x, t) for x in nrm), material=ridge.load_material('alpine'))"),
|
||||
'rays cache key ignores the refraction constant': ("R_EARTH, KREF, W, bool(detail)", "R_EARTH, W, bool(detail)"),
|
||||
'rays cache key ignores the eye elevation': ("round(float(P['eye_m']), 3), ", ""),
|
||||
'mosaic cache key ignores the tile list': ("sorted(tiles_for(p)), 3600", "3600"),
|
||||
}
|
||||
EQUIVALENT = {'fit: the error is looked for between four points': "the worst error of the best line is at the viewport's two ends for every distance and offset the bound is searched over (checked against a 20001-sample brute force in test_fit_px_is_the_continuous_error); the grid only guards a shape where it is not"} # mutant name -> one line on why it is behaviourally equivalent (reported, not run)
|
||||
def execute(edit):
|
||||
"""Run the fixtures on a COPY of the baker, with edit = (text, replacement) applied or None for the unmutated copy: (returncode or None if the text is gone, [(fixture, exception class, directory of the innermost traceback frame)] of every FAIL line, last stderr line)."""
|
||||
d = tempfile.mkdtemp(); shutil.copytree(SRC, os.path.join(d, 'src'), ignore=shutil.ignore_patterns('tests', '__pycache__'))
|
||||
try:
|
||||
if edit:
|
||||
a, b = edit; p = next((q for q in (os.path.join(d, 'src', f) for f in ('ridge.py', 'export.py')) if a in open(q).read()), None)
|
||||
if p is None: return None, [], 'the mutant text is in neither ridge.py nor export.py'
|
||||
s = open(p).read(); open(p, 'w').write(s.replace(a, b))
|
||||
r = subprocess.run([sys.executable, os.path.join(HERE, 'test_ridge.py')], env=dict(os.environ, RIDGE_SRC=os.path.join(d, 'src')), capture_output=True, text=True)
|
||||
finally: shutil.rmtree(d)
|
||||
fails = [(f[0][4:].strip(), f[1].strip(), os.path.dirname(os.path.abspath(f[2].strip()))) for f in (l.split(' | ', 3) for l in r.stdout.splitlines() if l.startswith('FAIL')) if len(f) == 4]
|
||||
return r.returncode, fails, (r.stderr.strip().splitlines() or ['no output'])[-1][:200]
|
||||
def run(item):
|
||||
"""KILLED: at least one fixture failed on an assertion the test code itself raised (an AssertionError whose innermost traceback frame lies in the tests directory). CRASHED: the run failed but no fixture did that (every FAIL is another exception, NameError or a numpy error and the like, or an assert inside the baker, or none printed, or the mutant text is gone), which proves nothing and fails the run. SURVIVED: every fixture passed."""
|
||||
name, (a, b) = item; rc, fails, err = execute((a, b)); asserts = [n for n, c, w in fails if c == 'AssertionError' and w == HERE]
|
||||
state = 'CRASHED ' if rc is None or (rc and not asserts) else 'KILLED ' if rc else 'SURVIVED '
|
||||
why = ', '.join(f'{n}[{c}{"" if w == HERE else " in " + os.path.basename(w)}]' for n, c, w in fails) if fails else err
|
||||
line = state + name + ' -> ' + why; print(line, file=sys.stderr, flush=True) # progress: a killed run keeps what finished
|
||||
return line, state != 'KILLED '
|
||||
def baseline():
|
||||
"""The unmutated copy must pass every fixture before any mutant means anything: a broken environment would kill them all."""
|
||||
rc, fails, err = execute(None)
|
||||
if rc or fails: print('BASELINE FAILED: the unmutated baker does not pass its fixtures: ' + (', '.join(f'{n}[{c}]' for n, c, w in fails) or err), file=sys.stderr, flush=True); sys.exit(2)
|
||||
print('BASELINE ok: the unmutated copy passes every fixture', file=sys.stderr, flush=True)
|
||||
if __name__ == '__main__':
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
baseline()
|
||||
with ThreadPoolExecutor(int(os.environ.get('MUTATE_JOBS', '6'))) as ex: res = list(ex.map(run, [(n, v) for n, v in MUTANTS.items() if n not in EQUIVALENT and all(w in n for w in sys.argv[1:])]))
|
||||
for line, _ in res: print(line, flush=True)
|
||||
for n, why in EQUIVALENT.items(): print('EQUIVALENT ' + n + ' -> ' + why)
|
||||
sys.exit(1 if any(sv for _, sv in res) else 0)
|
||||
|
|
@ -1,7 +1,7 @@
|
|||
#!/bin/sh
|
||||
# Usage: RIDGE_PY=<venv python> RIDGE_TILES=<tiles dir> tests/run.sh [test_ridge.py|mutate.py]
|
||||
# Usage: RIDGE_PY=<venv python> RIDGE_TILES=<tiles dir> tests/run.sh
|
||||
# RIDGE_WORK (cache dir) defaults to a fresh directory under $TMPDIR.
|
||||
: "${RIDGE_PY:?RIDGE_PY must name the python of the baker venv}"
|
||||
export RIDGE_WORK="${RIDGE_WORK:-${TMPDIR:-/tmp}/ridge-bake-work}"; mkdir -p "$RIDGE_WORK"
|
||||
HERE=$(cd "$(dirname "$0")" && pwd)
|
||||
exec "$RIDGE_PY" -I "$HERE/${1:-test_ridge.py}"
|
||||
exec "$RIDGE_PY" -I "$HERE/test_ridge.py"
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
"""Fixtures for the ridge baker (march, prefilter, coverage, seams, normals, cards, export). Plain asserts, no pytest needed: venv/bin/python tests/test_ridge.py (exit code 1 on failure).
|
||||
RIDGE_SRC selects the source directory (default ..) (the mutation runner points it at a patched copy).
|
||||
RIDGE_SRC selects the source directory (default ..).
|
||||
Synthetic terrain has a known right answer; the Vienna tests bake the real preset (its rays come from stage0: RIDGE_TILES needs the tiles, or a cached rays file must exist)."""
|
||||
import os, sys, math, json, shutil, tempfile, traceback
|
||||
SRC = os.environ.get('RIDGE_SRC') or os.path.join(os.path.dirname(os.path.abspath(__file__)), '..'); sys.path.insert(0, SRC) # RIDGE_WORK and RIDGE_TILES must be set (tests/run.sh sets them)
|
||||
|
|
@ -226,7 +226,7 @@ def _pins():
|
|||
assert abs(export.HFOV_MAX_DEG - 72 / 1.1) < 1e-12
|
||||
|
||||
def test_schema3():
|
||||
"""The manifest validates; a tile array of the wrong length, a missing apron, a file named for another tile, and any key of schema 2 left behind (the camera's heading range and offset, the window, the plane width, the card's median and scale, the whole-bake w and h) are refused; the schema file is pinned; the layout constants are pinned."""
|
||||
"""The manifest validates; a tile array of the wrong length, a missing card, a file named for another tile, an all-null card, and a wrong byte total are refused; the layout constants are pinned."""
|
||||
_pins(); d = tempfile.mkdtemp()
|
||||
try:
|
||||
b = _toy(); pk = export.pack(b); dest = _write(d, b, pk); m = json.load(open(dest / 'manifest.json')); export.validate_manifest(m); mk = lambda: json.loads(json.dumps(m))
|
||||
|
|
@ -236,15 +236,9 @@ def test_schema3():
|
|||
try: export.validate_manifest(x)
|
||||
except export.Refusal: return
|
||||
raise AssertionError(why)
|
||||
bad(lambda x: x['camera'].pop('r_max_forward_m'), 'a camera without its forward offset validated'); bad(lambda x: x['camera'].pop('r_max_m'), 'a camera without its offset validated')
|
||||
bad(lambda x: x['tiles'].pop(), 'a manifest of 31 tiles validated'); bad(lambda x: x['tiles'][3].pop(), 'a tile with a card missing validated'); bad(lambda x: x['tiles'][3].append(None), 'a tile with an extra card validated'); bad(lambda x: x['view'].pop('apron'), 'a missing apron validated')
|
||||
bad(lambda x: x['view'].update(apron=0), 'an apron of 0 validated'); bad(lambda x: x['tiles'][2][1]['colour'].update(file='card-1-t03-colour.webp'), 'a file named for another tile validated')
|
||||
bad(lambda x: x['tiles'].pop(), 'a manifest of 31 tiles validated'); bad(lambda x: x['tiles'][3].pop(), 'a tile with a card missing validated'); bad(lambda x: x['tiles'][3].append(None), 'a tile with an extra card validated')
|
||||
bad(lambda x: x['tiles'][2][1]['colour'].update(file='card-1-t03-colour.webp'), 'a file named for another tile validated')
|
||||
bad(lambda x: x['tiles'].__setitem__(slice(None), [[None] * 3 for _ in range(32)]), 'a card null in every tile validated'); bad(lambda x: x.update(bytes=x['bytes'] + 1), 'a wrong byte total validated')
|
||||
for where, key in (('camera', 'heading_max' + '_deg'), ('view', 'window' + '_deg'), ('view', 'plane' + '_w'), ('view', 'rows_above'), ('camera', 'r_m'), (None, 'w'), (None, 'h')): # schema 2's names are spelled in pieces: the baker's tree must hold none of them
|
||||
bad(lambda x: (x[where] if where else x).update({key: 1}), f'a leftover {key} validated')
|
||||
bad(lambda x: x['cards'][0].update(**{'median' + '_m': 1.0}), 'a leftover median validated'); bad(lambda x: x['cards'][0].update(scale=1.0), 'a leftover scale validated'); bad(lambda x: x['tiles'][0][0].update(scale=1.0), 'a tile entry with a scale validated')
|
||||
bad(lambda x: x['tiles'][0][0].update(distance_m='far'), 'a distance that is not a number validated'); bad(lambda x: x['place'].update(tz='Mars/Olympus'), 'a zone the system does not know validated')
|
||||
assert json.load(open(os.path.join(SRC, 'ridge-bake.schema.json'))) == json.loads(json.dumps(export.SCHEMA)), 'ridge-bake.schema.json is stale (export.py --write-schema)'
|
||||
finally: shutil.rmtree(d)
|
||||
def test_manifest_v3_writer():
|
||||
"""Two packs of one bake give the same bytes and bake_id; tiles[t][i] files are where the manifest says with the sizes it says and decode to tile_w + 2 apron columns; the bake_id is the sha256 of the files tile-major, then card, colour then geometry; the index points at the dir, a
|
||||
|
|
@ -268,7 +262,7 @@ def test_manifest_v3_writer():
|
|||
for i, e in enumerate(row):
|
||||
for kind in ('colour', 'geometry'): f = a / e[kind]['file']; assert f.stat().st_size == e[kind]['bytes'] and export.decode(f.read_bytes()).shape[:2] == (e['h'], export.TILE_W + 2 * export.APRON), (t, i, kind)
|
||||
assert m['bytes'] == sum(e[k]['bytes'] for row in m['tiles'] for e in row for k in ('colour', 'geometry')) and m['encoding']['normal'] == 'rt8' and m['curvature'] == dict(r_earth_m=ridge.R_EARTH, k_ref=ridge.KREF)
|
||||
idx = json.load(open(d + '/a/index.json')); export.validate(idx, export.SCHEMA['$defs']['index']); assert idx == dict(schema=1, default='toy', places={'toy': a.name})
|
||||
idx = json.load(open(d + '/a/index.json')); assert idx == dict(schema=1, default='toy', places={'toy': a.name})
|
||||
want = dict(credit_line='Contains modified Copernicus data: DEM © DLR e.V. 2010-2014 and © Airbus Defence and Space GmbH 2014-2018 provided under COPERNICUS by the European Union and ESA; all rights reserved.',
|
||||
licence='Copernicus DEM licence: free, full and open access, with the credit line shown', dem_source='Copernicus DEM GLO-30 (30 m)', url='https://spacedata.copernicus.eu/collections/copernicus-digital-elevation-model'); assert m['attribution'] == want, m['attribution']
|
||||
c = _write(d + '/a', b, pk); assert c.name == a.name; other = dict(b['place'], id='other'); _write(d + '/a', b, pk, place=other); assert json.load(open(d + '/a/index.json'))['default'] == 'toy'
|
||||
|
|
@ -721,5 +715,5 @@ if __name__ == '__main__':
|
|||
fails = 0
|
||||
for t in TESTS:
|
||||
try: t(); print("PASS", t.__name__)
|
||||
except Exception as e: fails += 1; print("FAIL", t.__name__, "|", type(e).__name__, "|", traceback.extract_tb(e.__traceback__)[-1].filename, "|", repr(e)[:300]) # name | class | file of the innermost frame | repr: mutate.py kills only on an AssertionError raised in this directory
|
||||
except Exception as e: fails += 1; print("FAIL", t.__name__, "|", type(e).__name__, "|", traceback.extract_tb(e.__traceback__)[-1].filename, "|", repr(e)[:300])
|
||||
print("failures:", fails); sys.exit(1 if fails else 0)
|
||||
|
|
|
|||
|
|
@ -16,7 +16,6 @@ import {
|
|||
} from 'folds';
|
||||
import { MatrixError } from 'matrix-js-sdk';
|
||||
import { Cursor } from '../plugins/text-area';
|
||||
import { PhoneHit } from '../styles/PhoneHit.css';
|
||||
import { syntaxErrorPosition } from '../utils/dom';
|
||||
import { AsyncStatus, useAsyncCallback } from '../hooks/useAsyncCallback';
|
||||
import { Page, PageHeader } from './page';
|
||||
|
|
@ -295,7 +294,7 @@ export function AccountDataEditor({
|
|||
</Chip>
|
||||
</Box>
|
||||
<Box shrink="No">
|
||||
<IconButton onClick={requestClose} variant="Surface" className={PhoneHit}>
|
||||
<IconButton onClick={requestClose} variant="Surface">
|
||||
<Icon src={Icons.Cross} />
|
||||
</IconButton>
|
||||
</Box>
|
||||
|
|
|
|||
|
|
@ -30,7 +30,6 @@ import {
|
|||
} from '../hooks/useKeyBackup';
|
||||
import { stopPropagation } from '../utils/keyboard';
|
||||
import { useRestoreBackupOnVerification } from '../hooks/useRestoreBackupOnVerification';
|
||||
import { PhoneHit } from '../styles/PhoneHit.css';
|
||||
|
||||
type BackupStatusProps = {
|
||||
enabled: boolean;
|
||||
|
|
@ -178,7 +177,6 @@ export function BackupRestoreTile({ crypto }: BackupRestoreTileProps) {
|
|||
<BackupSyncing count={remainingSession} />
|
||||
)}
|
||||
<IconButton
|
||||
className={PhoneHit}
|
||||
aria-pressed={!!menuCords}
|
||||
size="300"
|
||||
variant="Surface"
|
||||
|
|
|
|||
|
|
@ -30,7 +30,6 @@ import {
|
|||
} from '../hooks/useVerificationRequest';
|
||||
import { AsyncStatus, useAsyncCallback } from '../hooks/useAsyncCallback';
|
||||
import { ContainerColor } from '../styles/ContainerColor.css';
|
||||
import { PhoneHit } from '../styles/PhoneHit.css';
|
||||
|
||||
const DialogHeaderStyles: CSSProperties = {
|
||||
padding: `0 ${config.space.S200} 0 ${config.space.S400}`,
|
||||
|
|
@ -262,7 +261,7 @@ export function DeviceVerification({ request, onExit }: DeviceVerificationProps)
|
|||
<Box grow="Yes">
|
||||
<Text size="H4">Device Verification</Text>
|
||||
</Box>
|
||||
<IconButton className={PhoneHit} size="300" radii="300" onClick={handleCancel}>
|
||||
<IconButton size="300" radii="300" onClick={handleCancel}>
|
||||
<Icon src={Icons.Cross} />
|
||||
</IconButton>
|
||||
</Header>
|
||||
|
|
|
|||
|
|
@ -25,7 +25,6 @@ import { ActionUIA, ActionUIAFlowsLoader } from './ActionUIA';
|
|||
import { useMatrixClient } from '../hooks/useMatrixClient';
|
||||
import { useAlive } from '../hooks/useAlive';
|
||||
import { UseStateProvider } from './UseStateProvider';
|
||||
import { PhoneHit } from '../styles/PhoneHit.css';
|
||||
|
||||
type UIACallback<T> = (
|
||||
authDict: AuthDict | null
|
||||
|
|
@ -302,7 +301,7 @@ export const DeviceVerificationSetup = forwardRef<HTMLDivElement, DeviceVerifica
|
|||
<Box grow="Yes">
|
||||
<Text size="H4">Setup Device Verification</Text>
|
||||
</Box>
|
||||
<IconButton className={PhoneHit} size="300" radii="300" onClick={onCancel}>
|
||||
<IconButton size="300" radii="300" onClick={onCancel}>
|
||||
<Icon src={Icons.Cross} />
|
||||
</IconButton>
|
||||
</Header>
|
||||
|
|
@ -337,7 +336,7 @@ export const DeviceVerificationReset = forwardRef<HTMLDivElement, DeviceVerifica
|
|||
<Box grow="Yes">
|
||||
<Text size="H4">Reset Device Verification</Text>
|
||||
</Box>
|
||||
<IconButton className={PhoneHit} size="300" radii="300" onClick={onCancel}>
|
||||
<IconButton size="300" radii="300" onClick={onCancel}>
|
||||
<Icon src={Icons.Cross} />
|
||||
</IconButton>
|
||||
</Header>
|
||||
|
|
|
|||
|
|
@ -27,7 +27,6 @@ import { AsyncStatus } from '../../hooks/useAsyncCallback';
|
|||
import { useZoom } from '../../hooks/useZoom';
|
||||
import { createPage, usePdfDocumentLoader, usePdfJSLoader } from '../../plugins/pdfjs-dist';
|
||||
import { stopPropagation } from '../../utils/keyboard';
|
||||
import { PhoneHit, PhoneHitSpread24 } from '../../styles/PhoneHit.css';
|
||||
|
||||
export type PdfViewerProps = {
|
||||
name: string;
|
||||
|
|
@ -109,7 +108,7 @@ export const PdfViewer = as<'div', PdfViewerProps>(
|
|||
<Box className={classNames(css.PdfViewer, className)} direction="Column" {...props} ref={ref}>
|
||||
<Header className={css.PdfViewerHeader} size="400">
|
||||
<Box grow="Yes" alignItems="Center" gap="200">
|
||||
<IconButton className={PhoneHit} size="300" radii="300" onClick={requestClose}>
|
||||
<IconButton size="300" radii="300" onClick={requestClose}>
|
||||
<Icon size="50" src={Icons.ArrowLeft} />
|
||||
</IconButton>
|
||||
<Text size="T300" truncate>
|
||||
|
|
@ -118,7 +117,6 @@ export const PdfViewer = as<'div', PdfViewerProps>(
|
|||
</Box>
|
||||
<Box shrink="No" alignItems="Center" gap="200">
|
||||
<IconButton
|
||||
className={PhoneHitSpread24}
|
||||
variant={zoom < 1 ? 'Success' : 'SurfaceVariant'}
|
||||
outlined={zoom < 1}
|
||||
size="300"
|
||||
|
|
@ -132,7 +130,6 @@ export const PdfViewer = as<'div', PdfViewerProps>(
|
|||
<Text size="B300">{Math.round(zoom * 100)}%</Text>
|
||||
</Chip>
|
||||
<IconButton
|
||||
className={PhoneHitSpread24}
|
||||
variant={zoom > 1 ? 'Success' : 'SurfaceVariant'}
|
||||
outlined={zoom > 1}
|
||||
size="300"
|
||||
|
|
|
|||
|
|
@ -13,7 +13,6 @@ import {
|
|||
IconButton,
|
||||
} from 'folds';
|
||||
import FocusTrap from 'focus-trap-react';
|
||||
import { PhoneHit } from '../styles/PhoneHit.css';
|
||||
|
||||
export type UIAFlowOverlayProps = {
|
||||
currentStep: number;
|
||||
|
|
@ -54,7 +53,6 @@ export function UIAFlowOverlay({
|
|||
>
|
||||
{(anchorRef) => (
|
||||
<IconButton
|
||||
className={PhoneHit}
|
||||
ref={anchorRef}
|
||||
variant="Critical"
|
||||
size="300"
|
||||
|
|
|
|||
|
|
@ -1,5 +1,9 @@
|
|||
import { style } from '@vanilla-extract/css';
|
||||
import { globalStyle, style } from '@vanilla-extract/css';
|
||||
import { color, config, DefaultReset, toRem } from 'folds';
|
||||
import { ICON_BUTTON_CLASS } from '../../../phoneGlyph.css';
|
||||
import { MOBILE_BREAKPOINT } from '../../hooks/useScreenSize';
|
||||
|
||||
const PHONE = `screen and (max-width: ${MOBILE_BREAKPOINT}px)`;
|
||||
|
||||
export const Editor = style([
|
||||
DefaultReset,
|
||||
|
|
@ -19,6 +23,10 @@ export const EditorOptions = style([
|
|||
},
|
||||
]);
|
||||
|
||||
globalStyle(`${EditorOptions} .${ICON_BUTTON_CLASS}`, {
|
||||
'@media': { [PHONE]: { marginInline: 6 } },
|
||||
});
|
||||
|
||||
export const EditorTextareaScroll = style({});
|
||||
|
||||
export const EditorTextarea = style([
|
||||
|
|
@ -67,6 +75,10 @@ export const EditorToolbar = style({
|
|||
padding: config.space.S100,
|
||||
});
|
||||
|
||||
globalStyle(`${EditorToolbar} .${ICON_BUTTON_CLASS}`, {
|
||||
'@media': { [PHONE]: { marginInline: 4 } },
|
||||
});
|
||||
|
||||
export const MarkdownBtnBox = style({
|
||||
paddingRight: config.space.S100,
|
||||
});
|
||||
|
|
|
|||
|
|
@ -36,7 +36,6 @@ import { KeySymbol } from '../../utils/key-symbol';
|
|||
import { useSetting } from '../../state/hooks/settings';
|
||||
import { settingsAtom } from '../../state/settings';
|
||||
import { stopPropagation } from '../../utils/keyboard';
|
||||
import { PhoneHit, PhoneHitRoom36, PhoneHitSpread36 } from '../../styles/PhoneHit.css';
|
||||
|
||||
function BtnTooltip({ text, shortCode }: { text: string; shortCode?: string }) {
|
||||
return (
|
||||
|
|
@ -73,7 +72,6 @@ export function MarkButton({ format, icon, tooltip }: MarkButtonProps) {
|
|||
<TooltipProvider tooltip={tooltip} delay={500}>
|
||||
{(triggerRef) => (
|
||||
<IconButton
|
||||
className={PhoneHitSpread36}
|
||||
ref={triggerRef}
|
||||
variant="SurfaceVariant"
|
||||
onClick={handleClick}
|
||||
|
|
@ -106,7 +104,6 @@ export function BlockButton({ format, icon, tooltip }: BlockButtonProps) {
|
|||
<TooltipProvider tooltip={tooltip} delay={500}>
|
||||
{(triggerRef) => (
|
||||
<IconButton
|
||||
className={PhoneHitSpread36}
|
||||
ref={triggerRef}
|
||||
variant="SurfaceVariant"
|
||||
onClick={handleClick}
|
||||
|
|
@ -166,7 +163,6 @@ export function HeadingBlockButton() {
|
|||
>
|
||||
{(triggerRef) => (
|
||||
<IconButton
|
||||
className={PhoneHitRoom36}
|
||||
ref={triggerRef}
|
||||
onClick={() => handleMenuSelect(1)}
|
||||
size="400"
|
||||
|
|
@ -182,7 +178,6 @@ export function HeadingBlockButton() {
|
|||
>
|
||||
{(triggerRef) => (
|
||||
<IconButton
|
||||
className={PhoneHitRoom36}
|
||||
ref={triggerRef}
|
||||
onClick={() => handleMenuSelect(2)}
|
||||
size="400"
|
||||
|
|
@ -198,7 +193,6 @@ export function HeadingBlockButton() {
|
|||
>
|
||||
{(triggerRef) => (
|
||||
<IconButton
|
||||
className={PhoneHitRoom36}
|
||||
ref={triggerRef}
|
||||
onClick={() => handleMenuSelect(3)}
|
||||
size="400"
|
||||
|
|
@ -214,7 +208,6 @@ export function HeadingBlockButton() {
|
|||
}
|
||||
>
|
||||
<IconButton
|
||||
className={PhoneHit}
|
||||
style={{ width: 'unset' }}
|
||||
variant="SurfaceVariant"
|
||||
onClick={handleMenuOpen}
|
||||
|
|
@ -246,7 +239,6 @@ export function ExitFormatting({ tooltip }: ExitFormattingProps) {
|
|||
<TooltipProvider tooltip={tooltip} delay={500}>
|
||||
{(triggerRef) => (
|
||||
<IconButton
|
||||
className={PhoneHit}
|
||||
ref={triggerRef}
|
||||
variant="SurfaceVariant"
|
||||
onClick={handleClick}
|
||||
|
|
@ -352,7 +344,6 @@ export function Toolbar() {
|
|||
>
|
||||
{(triggerRef) => (
|
||||
<IconButton
|
||||
className={PhoneHit}
|
||||
ref={triggerRef}
|
||||
variant="SurfaceVariant"
|
||||
onClick={() => setIsMarkdown(!isMarkdown)}
|
||||
|
|
|
|||
|
|
@ -14,7 +14,6 @@ import {
|
|||
} from 'folds';
|
||||
import classNames from 'classnames';
|
||||
import * as css from './styles.css';
|
||||
import { PhoneHit } from '../../../styles/PhoneHit.css';
|
||||
|
||||
export function Sidebar({ children }: { children: ReactNode }) {
|
||||
return (
|
||||
|
|
@ -69,7 +68,6 @@ function SidebarBtn<T extends string>({
|
|||
>
|
||||
{(ref) => (
|
||||
<IconButton
|
||||
className={PhoneHit}
|
||||
aria-pressed={active}
|
||||
aria-labelledby={`SidebarStackItem-${id}-label`}
|
||||
ref={ref}
|
||||
|
|
|
|||
|
|
@ -24,7 +24,6 @@ import { useMediaAuthentication } from '../../hooks/useMediaAuthentication';
|
|||
import { useOpenUserRoomProfile } from '../../state/hooks/userRoomProfile';
|
||||
import { useSpaceOptionally } from '../../hooks/useSpace';
|
||||
import { getMouseEventCords } from '../../utils/dom';
|
||||
import { PhoneHit } from '../../styles/PhoneHit.css';
|
||||
|
||||
export type EventReadersProps = {
|
||||
room: Room;
|
||||
|
|
@ -53,7 +52,7 @@ export const EventReaders = as<'div', EventReadersProps>(
|
|||
<Box grow="Yes">
|
||||
<Text size="H3">Seen by</Text>
|
||||
</Box>
|
||||
<IconButton className={PhoneHit} size="300" onClick={requestClose}>
|
||||
<IconButton size="300" onClick={requestClose}>
|
||||
<Icon src={Icons.Cross} />
|
||||
</IconButton>
|
||||
</Header>
|
||||
|
|
|
|||
|
|
@ -2,7 +2,6 @@ import React from 'react';
|
|||
import classNames from 'classnames';
|
||||
import { Box, Chip, Header, Icon, IconButton, Icons, Text, as } from 'folds';
|
||||
import * as css from './ImageEditor.css';
|
||||
import { PhoneHit } from '../../styles/PhoneHit.css';
|
||||
|
||||
export type ImageEditorProps = {
|
||||
name: string;
|
||||
|
|
@ -25,7 +24,7 @@ export const ImageEditor = as<'div', ImageEditorProps>(
|
|||
>
|
||||
<Header className={css.ImageEditorHeader} size="400">
|
||||
<Box grow="Yes" alignItems="Center" gap="200">
|
||||
<IconButton className={PhoneHit} size="300" radii="300" onClick={requestClose}>
|
||||
<IconButton size="300" radii="300" onClick={requestClose}>
|
||||
<Icon size="50" src={Icons.ArrowLeft} />
|
||||
</IconButton>
|
||||
<Text size="T300" truncate>
|
||||
|
|
|
|||
|
|
@ -1,7 +1,6 @@
|
|||
import React from 'react';
|
||||
import { Box, IconButton, Text, Icon, Icons, Scroll, Chip } from 'folds';
|
||||
import { PackAddress } from '../../plugins/custom-emoji';
|
||||
import { PhoneHit } from '../../styles/PhoneHit.css';
|
||||
import { Page, PageHeader, PageContent } from '../page';
|
||||
import { useMatrixClient } from '../../hooks/useMatrixClient';
|
||||
import { RoomImagePack } from './RoomImagePack';
|
||||
|
|
@ -30,7 +29,7 @@ export function ImagePackView({ address, requestClose }: ImagePackViewProps) {
|
|||
</Chip>
|
||||
</Box>
|
||||
<Box shrink="No">
|
||||
<IconButton onClick={requestClose} variant="Surface" className={PhoneHit}>
|
||||
<IconButton onClick={requestClose} variant="Surface">
|
||||
<Icon src={Icons.Cross} />
|
||||
</IconButton>
|
||||
</Box>
|
||||
|
|
|
|||
|
|
@ -7,7 +7,6 @@ import * as css from './ImageViewer.css';
|
|||
import { useZoom } from '../../hooks/useZoom';
|
||||
import { usePan } from '../../hooks/usePan';
|
||||
import { downloadMedia } from '../../utils/matrix';
|
||||
import { PhoneHit, PhoneHitSpread24 } from '../../styles/PhoneHit.css';
|
||||
|
||||
export type ImageViewerProps = {
|
||||
alt: string;
|
||||
|
|
@ -34,7 +33,7 @@ export const ImageViewer = as<'div', ImageViewerProps>(
|
|||
>
|
||||
<Header className={css.ImageViewerHeader} size="400">
|
||||
<Box grow="Yes" alignItems="Center" gap="200">
|
||||
<IconButton className={PhoneHit} size="300" radii="300" onClick={requestClose}>
|
||||
<IconButton size="300" radii="300" onClick={requestClose}>
|
||||
<Icon size="50" src={Icons.ArrowLeft} />
|
||||
</IconButton>
|
||||
<Text size="T300" truncate>
|
||||
|
|
@ -43,7 +42,6 @@ export const ImageViewer = as<'div', ImageViewerProps>(
|
|||
</Box>
|
||||
<Box shrink="No" alignItems="Center" gap="200">
|
||||
<IconButton
|
||||
className={PhoneHitSpread24}
|
||||
variant={zoom < 1 ? 'Success' : 'SurfaceVariant'}
|
||||
outlined={zoom < 1}
|
||||
size="300"
|
||||
|
|
@ -57,7 +55,6 @@ export const ImageViewer = as<'div', ImageViewerProps>(
|
|||
<Text size="B300">{Math.round(zoom * 100)}%</Text>
|
||||
</Chip>
|
||||
<IconButton
|
||||
className={PhoneHitSpread24}
|
||||
variant={zoom > 1 ? 'Success' : 'SurfaceVariant'}
|
||||
outlined={zoom > 1}
|
||||
size="300"
|
||||
|
|
|
|||
|
|
@ -42,7 +42,6 @@ import { AsyncStatus, useAsyncCallback } from '../../hooks/useAsyncCallback';
|
|||
import { useMatrixClient } from '../../hooks/useMatrixClient';
|
||||
import { BreakWord } from '../../styles/Text.css';
|
||||
import { useAlive } from '../../hooks/useAlive';
|
||||
import { PhoneHit } from '../../styles/PhoneHit.css';
|
||||
|
||||
const SEARCH_OPTIONS: UseAsyncSearchOptions = {
|
||||
limit: 1000,
|
||||
|
|
@ -174,7 +173,7 @@ export function InviteUserPrompt({ room, requestClose }: InviteUserProps) {
|
|||
</Text>
|
||||
</Box>
|
||||
<Box shrink="No">
|
||||
<IconButton className={PhoneHit} size="300" radii="300" onClick={requestClose}>
|
||||
<IconButton size="300" radii="300" onClick={requestClose}>
|
||||
<Icon src={Icons.Cross} />
|
||||
</IconButton>
|
||||
</Box>
|
||||
|
|
|
|||
|
|
@ -20,7 +20,6 @@ import { stopPropagation } from '../../utils/keyboard';
|
|||
import { isRoomAlias, isRoomId } from '../../utils/matrix';
|
||||
import { parseMatrixToRoom, parseMatrixToRoomEvent, testMatrixTo } from '../../plugins/matrix-to';
|
||||
import { tryDecodeURIComponent } from '../../utils/dom';
|
||||
import { PhoneHit } from '../../styles/PhoneHit.css';
|
||||
|
||||
type JoinAddressProps = {
|
||||
onOpen: (roomIdOrAlias: string, via?: string[], eventId?: string) => void;
|
||||
|
|
@ -83,7 +82,7 @@ export function JoinAddressPrompt({ onOpen, onCancel }: JoinAddressProps) {
|
|||
<Box grow="Yes">
|
||||
<Text size="H4">Join with Address</Text>
|
||||
</Box>
|
||||
<IconButton className={PhoneHit} size="300" onClick={onCancel} radii="300">
|
||||
<IconButton size="300" onClick={onCancel} radii="300">
|
||||
<Icon src={Icons.Cross} />
|
||||
</IconButton>
|
||||
</Header>
|
||||
|
|
|
|||
|
|
@ -20,7 +20,6 @@ import { MatrixError } from 'matrix-js-sdk';
|
|||
import { useMatrixClient } from '../../hooks/useMatrixClient';
|
||||
import { AsyncStatus, useAsyncCallback } from '../../hooks/useAsyncCallback';
|
||||
import { stopPropagation } from '../../utils/keyboard';
|
||||
import { PhoneHit } from '../../styles/PhoneHit.css';
|
||||
|
||||
type LeaveRoomPromptProps = {
|
||||
roomId: string;
|
||||
|
|
@ -69,7 +68,7 @@ export function LeaveRoomPrompt({ roomId, onDone, onCancel }: LeaveRoomPromptPro
|
|||
<Box grow="Yes">
|
||||
<Text size="H4">Leave Room</Text>
|
||||
</Box>
|
||||
<IconButton className={PhoneHit} size="300" onClick={onCancel} radii="300">
|
||||
<IconButton size="300" onClick={onCancel} radii="300">
|
||||
<Icon src={Icons.Cross} />
|
||||
</IconButton>
|
||||
</Header>
|
||||
|
|
|
|||
|
|
@ -20,7 +20,6 @@ import { MatrixError } from 'matrix-js-sdk';
|
|||
import { useMatrixClient } from '../../hooks/useMatrixClient';
|
||||
import { AsyncStatus, useAsyncCallback } from '../../hooks/useAsyncCallback';
|
||||
import { stopPropagation } from '../../utils/keyboard';
|
||||
import { PhoneHit } from '../../styles/PhoneHit.css';
|
||||
|
||||
type LeaveSpacePromptProps = {
|
||||
roomId: string;
|
||||
|
|
@ -69,7 +68,7 @@ export function LeaveSpacePrompt({ roomId, onDone, onCancel }: LeaveSpacePromptP
|
|||
<Box grow="Yes">
|
||||
<Text size="H4">Leave Space</Text>
|
||||
</Box>
|
||||
<IconButton className={PhoneHit} size="300" onClick={onCancel} radii="300">
|
||||
<IconButton size="300" onClick={onCancel} radii="300">
|
||||
<Icon src={Icons.Cross} />
|
||||
</IconButton>
|
||||
</Header>
|
||||
|
|
|
|||
|
|
@ -2,7 +2,6 @@ import { Badge, Box, Icon, IconButton, Icons, Spinner, Text, as, toRem } from 'f
|
|||
import React, { ReactNode, useCallback } from 'react';
|
||||
import { EncryptedAttachmentInfo } from 'browser-encrypt-attachment';
|
||||
import FileSaver from 'file-saver';
|
||||
import { PhoneHit } from '../../styles/PhoneHit.css';
|
||||
import { mimeTypeToExt } from '../../utils/mimeTypes';
|
||||
import { useMatrixClient } from '../../hooks/useMatrixClient';
|
||||
import { useMediaAuthentication } from '../../hooks/useMediaAuthentication';
|
||||
|
|
@ -49,7 +48,6 @@ export function FileDownloadButton({ filename, url, mimeType, encInfo }: FileDow
|
|||
variant={hasError ? 'Critical' : 'SurfaceVariant'}
|
||||
size="300"
|
||||
radii="300"
|
||||
className={PhoneHit}
|
||||
>
|
||||
{downloading ? (
|
||||
<Spinner size="100" variant={hasError ? 'Critical' : 'Secondary'} />
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
import { createVar, style } from '@vanilla-extract/css';
|
||||
import { DefaultReset, FocusOutline, color, config, toRem } from 'folds';
|
||||
import { MOBILE_BREAKPOINT } from '../../hooks/useScreenSize';
|
||||
import { PHONE_TAP } from '../../styles/PhoneHit.css';
|
||||
import { PHONE_TAP } from '../../../phoneGlyph.css';
|
||||
|
||||
const PHONE = `screen and (max-width: ${MOBILE_BREAKPOINT}px)`;
|
||||
const Container = createVar();
|
||||
|
|
|
|||
|
|
@ -3,7 +3,6 @@ import React, { ReactNode, useCallback, useRef, useState } from 'react';
|
|||
import { Badge, Chip, Icon, IconButton, Icons, ProgressBar, Spinner, Text, toRem } from 'folds';
|
||||
import { EncryptedAttachmentInfo } from 'browser-encrypt-attachment';
|
||||
import { Range } from 'react-range';
|
||||
import { PhoneHitSpread24 } from '../../../styles/PhoneHit.css';
|
||||
import { useMatrixClient } from '../../../hooks/useMatrixClient';
|
||||
import { AsyncStatus, useAsyncCallback } from '../../../hooks/useAsyncCallback';
|
||||
import { IAudioInfo } from '../../../../types/matrix/common';
|
||||
|
|
@ -160,7 +159,6 @@ export function AudioContent({
|
|||
variant="SurfaceVariant"
|
||||
size="300"
|
||||
radii="Pill"
|
||||
className={PhoneHitSpread24}
|
||||
onClick={() => setMute(!mute)}
|
||||
aria-pressed={mute}
|
||||
>
|
||||
|
|
|
|||
|
|
@ -1,48 +0,0 @@
|
|||
import { readFileSync } from 'fs';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import zlib from 'zlib';
|
||||
import { compile, processVanillaFile } from '@vanilla-extract/integration';
|
||||
|
||||
// A long reply quote (nowrap) sized the own-message row to 782px on a 390px phone. The row, the column and the bubble
|
||||
// must be able to shrink to their parent, so pin the emitted declarations (as phoneTapTargets.test.ts does).
|
||||
const emitted = async () => {
|
||||
const filePath = `${process.cwd()}/src/app/components/message/layout/layout.css.ts`;
|
||||
const { source } = await compile({ filePath, cwd: process.cwd(), identOption: 'debug' });
|
||||
const code = await processVanillaFile({ source, filePath, identOption: 'debug' });
|
||||
const bytes = Buffer.from(
|
||||
(code.match(/source=#?([A-Za-z0-9+/=]+)/) as RegExpMatchArray)[1],
|
||||
'base64'
|
||||
);
|
||||
return (bytes[0] === 0x1f && bytes[1] === 0x8b ? zlib.gunzipSync(bytes) : bytes).toString();
|
||||
};
|
||||
|
||||
const declarations = (css: string, className: string): string[] => {
|
||||
const rule = new RegExp(`^\\.layout_${className}__[\\w-]+ \\{\\n([^}]*)\\}`, 'm').exec(css);
|
||||
expect(rule, `no .layout_${className} rule emitted`).toBeTruthy();
|
||||
return (rule as RegExpExecArray)[1].split('\n').map((l) => l.trim().replace(/;$/, ''));
|
||||
};
|
||||
|
||||
describe('bubble rows shrink to their column', () => {
|
||||
it.each([
|
||||
['BubbleColumn', ['min-width: 0']],
|
||||
['BubbleContentRow', ['min-width: 0', 'max-width: 100%']],
|
||||
['BubbleContent', ['min-width: 0']],
|
||||
])('%s', async (name, expected) => {
|
||||
const css = await emitted();
|
||||
expect(declarations(css, name)).toEqual(expect.arrayContaining(expected));
|
||||
});
|
||||
|
||||
it('BubbleContent keeps its 800px cap inside the column width', async () => {
|
||||
const css = await emitted();
|
||||
expect(declarations(css, 'BubbleContent').join('\n')).toMatch(/max-width: min\(100%, 50rem\)/);
|
||||
});
|
||||
|
||||
it('Bubble.tsx puts BubbleColumn on the column and BubbleContentRow on the row', () => {
|
||||
const tsx = readFileSync(
|
||||
`${process.cwd()}/src/app/components/message/layout/Bubble.tsx`,
|
||||
'utf8'
|
||||
);
|
||||
expect(tsx).toMatch(/classNames\(css\.BubbleColumn,/);
|
||||
expect(tsx).toMatch(/<Box className=\{css\.BubbleContentRow\}>/);
|
||||
});
|
||||
});
|
||||
|
|
@ -1,40 +0,0 @@
|
|||
import { describe, expect, it } from 'vitest';
|
||||
import { classifyPose, messagePose } from './sentiment';
|
||||
|
||||
describe('classifyPose', () => {
|
||||
it.each([
|
||||
['annoyed', 'ugh, this again'],
|
||||
['surprised', 'wow, no way'],
|
||||
['amused', 'hahaha that is funny'],
|
||||
['happy', 'thanks, great work'],
|
||||
['thinking', 'should we ship it?'],
|
||||
['neutral', 'Merged the branch.'],
|
||||
['neutral', 'sorry, that failed with an error'],
|
||||
])('%s', (label, text) => expect(classifyPose(text)).toBe(label));
|
||||
it('is neutral for empty or non-string text', () => {
|
||||
expect(classifyPose('')).toBe('neutral');
|
||||
expect(classifyPose(undefined)).toBe('neutral');
|
||||
expect(classifyPose(5)).toBe('neutral');
|
||||
});
|
||||
it('is deterministic', () => {
|
||||
expect(classifyPose('thanks?')).toBe(classifyPose('thanks?'));
|
||||
});
|
||||
});
|
||||
|
||||
describe('messagePose', () => {
|
||||
it('lets an explicit label win over the text', () => {
|
||||
expect(messagePose('aqua', { body: 'thanks!', 'org.gamecult.pose': 'annoyed' })).toBe(
|
||||
'annoyed'
|
||||
);
|
||||
});
|
||||
it('keeps an unknown explicit label neutral instead of classifying', () => {
|
||||
expect(messagePose('aqua', { body: 'thanks!', 'org.gamecult.pose': 'conduct' })).toBe(
|
||||
'neutral'
|
||||
);
|
||||
});
|
||||
it('classifies when there is no label, and never outputs a signature label', () => {
|
||||
expect(messagePose('aqua', { body: 'thanks!' })).toBe('happy');
|
||||
expect(messagePose('kiko', { body: 'sorry' })).toBe('neutral');
|
||||
expect(messagePose('aqua', {})).toBe('neutral');
|
||||
});
|
||||
});
|
||||
|
|
@ -1,35 +0,0 @@
|
|||
import { POSE_KEY, NEUTRAL, resolvePose } from './poses';
|
||||
|
||||
// catalogue.json beside this file is a vendored copy of /opt/commons/cast-art/poses/catalogue.json
|
||||
// (npm run sync:poses); nothing else publishes it to the browser.
|
||||
// Local sentiment -> pose label. A lexicon over the message text, no network, no model: the
|
||||
// same text always gives the same pose. Rules are tried in order and the first hit wins, so a
|
||||
// message that says "wow" and "thanks" reads as surprised. Only the shared labels (identical art
|
||||
// for all eight Minds, catalogue.json) are ever output; signature labels are explicit-only.
|
||||
const RULES: [string, RegExp][] = [
|
||||
['annoyed', /\b(annoy\w*|ugh+|argh+|frustrat\w*|again\?|why won'?t|stop it)\b/i],
|
||||
['surprised', /\b(wow|whoa|woah|omg|no way|unexpected\w*|surpris\w*|wait,? what)\b|[?!]{2,}/i],
|
||||
[
|
||||
'determined',
|
||||
/\b(let'?s (go|do|fix|ship)|on it|i'?ll (fix|do|handle)|will do|fixing|resolved?)\b/i,
|
||||
],
|
||||
['amused', /\b(ha(ha)+|lol|lmao|rofl|funny|hilarious)\b|😂|🤣/i],
|
||||
[
|
||||
'happy',
|
||||
/\b(thanks?|thank you|thx|great|awesome|nice|love|perfect|excellent|yay|congrats)\b|🎉|😊/i,
|
||||
],
|
||||
['thinking', /\?\s*$|\b(hmm+|maybe|perhaps|i wonder|not sure|how (do|does|about)|what if)\b/i],
|
||||
];
|
||||
|
||||
export const classifyPose = (text: unknown): string => {
|
||||
if (typeof text !== 'string') return NEUTRAL;
|
||||
const hit = RULES.find(([, re]) => re.test(text));
|
||||
return hit ? hit[0] : NEUTRAL;
|
||||
};
|
||||
|
||||
// An explicit org.gamecult.pose label always wins, even when it is unknown (then neutral).
|
||||
// Only events with no label are read for sentiment.
|
||||
export const messagePose = (mind: string, content: Record<string, unknown>): string =>
|
||||
content[POSE_KEY] !== undefined
|
||||
? resolvePose(mind, content[POSE_KEY])
|
||||
: resolvePose(mind, classifyPose(content.body));
|
||||
|
|
@ -2,7 +2,6 @@ import { ComplexStyleRule, StyleRule, createVar, globalStyle, style } from '@van
|
|||
import { RecipeVariants, recipe } from '@vanilla-extract/recipes';
|
||||
import { ContainerColor, DefaultReset, Disabled, RadiiVariant, color, config, toRem } from 'folds';
|
||||
import { surfaceInk } from '../../features/scene/sceneShell.css';
|
||||
import { skyLabelInk } from '../../features/scene/skyLabelInk';
|
||||
|
||||
// Wash strengths over the scene: rows and labels are faint, and hover, selected and pressed rows
|
||||
// are three distinct steps above them.
|
||||
|
|
@ -259,7 +258,7 @@ phoneLabel(`.${NavItemBase}:has(.${NavLink}:active) ${label}`, {
|
|||
textDecorationLine: 'underline',
|
||||
});
|
||||
phoneLabel(`:root[data-scene] ${label}`, {
|
||||
color: skyLabelInk('inherit'),
|
||||
color: 'inherit',
|
||||
textShadow: `0 0 3px ${surfaceInk}, 0 0 8px ${surfaceInk}`,
|
||||
});
|
||||
|
||||
|
|
|
|||
|
|
@ -1,7 +1,6 @@
|
|||
import React, { ComponentProps, forwardRef } from 'react';
|
||||
import { Icon, IconButton, Input, config, Icons } from 'folds';
|
||||
import { UseStateProvider } from '../UseStateProvider';
|
||||
import { PhoneHit } from '../../styles/PhoneHit.css';
|
||||
|
||||
type PasswordInputProps = Omit<ComponentProps<typeof Input>, 'type' | 'size'> & {
|
||||
size: '400' | '500';
|
||||
|
|
@ -24,7 +23,6 @@ export const PasswordInput = forwardRef<HTMLInputElement, PasswordInputProps>(
|
|||
<>
|
||||
{after}
|
||||
<IconButton
|
||||
className={PhoneHit}
|
||||
onClick={() => setVisible(!visible)}
|
||||
type="button"
|
||||
variant={visible ? 'Warning' : variant}
|
||||
|
|
|
|||
|
|
@ -4,7 +4,6 @@ import classNames from 'classnames';
|
|||
import Linkify from 'linkify-react';
|
||||
import * as css from './style.css';
|
||||
import { LINKIFY_OPTS, scaleSystemEmoji } from '../../plugins/react-custom-html-parser';
|
||||
import { PhoneHit } from '../../styles/PhoneHit.css';
|
||||
|
||||
export const RoomTopicViewer = as<
|
||||
'div',
|
||||
|
|
@ -27,7 +26,7 @@ export const RoomTopicViewer = as<
|
|||
{name}
|
||||
</Text>
|
||||
</Box>
|
||||
<IconButton className={PhoneHit} size="300" onClick={requestClose} radii="300">
|
||||
<IconButton size="300" onClick={requestClose} radii="300">
|
||||
<Icon src={Icons.Cross} />
|
||||
</IconButton>
|
||||
</Header>
|
||||
|
|
|
|||
|
|
@ -5,7 +5,6 @@ import { Box, Chip, Header, Icon, IconButton, Icons, Scroll, Text, as } from 'fo
|
|||
import { ErrorBoundary } from 'react-error-boundary';
|
||||
import * as css from './TextViewer.css';
|
||||
import { copyToClipboard } from '../../utils/dom';
|
||||
import { PhoneHit } from '../../styles/PhoneHit.css';
|
||||
|
||||
const ReactPrism = lazy(() => import('../../plugins/react-prism/ReactPrism'));
|
||||
|
||||
|
|
@ -54,7 +53,7 @@ export const TextViewer = as<'div', TextViewerProps>(
|
|||
>
|
||||
<Header className={css.TextViewerHeader} size="400">
|
||||
<Box grow="Yes" alignItems="Center" gap="200">
|
||||
<IconButton className={PhoneHit} size="300" radii="300" onClick={requestClose}>
|
||||
<IconButton size="300" radii="300" onClick={requestClose}>
|
||||
<Icon size="50" src={Icons.ArrowLeft} />
|
||||
</IconButton>
|
||||
<Text size="T300" truncate>
|
||||
|
|
|
|||
|
|
@ -4,7 +4,6 @@ import { AuthType } from 'matrix-js-sdk';
|
|||
import { StageComponentProps } from './types';
|
||||
import { ErrorCode } from '../../cs-errorcode';
|
||||
import { PasswordInput } from '../password-input';
|
||||
import { PhoneHit } from '../../styles/PhoneHit.css';
|
||||
|
||||
export function PasswordStage({
|
||||
stageData,
|
||||
|
|
@ -46,7 +45,7 @@ export function PasswordStage({
|
|||
<Box grow="Yes">
|
||||
<Text size="H4">Account Password</Text>
|
||||
</Box>
|
||||
<IconButton className={PhoneHit} size="300" onClick={onCancel} radii="300">
|
||||
<IconButton size="300" onClick={onCancel} radii="300">
|
||||
<Icon src={Icons.Cross} />
|
||||
</IconButton>
|
||||
</Header>
|
||||
|
|
|
|||
|
|
@ -1,7 +1,6 @@
|
|||
import { Box, Button, color, config, Dialog, Header, Icon, IconButton, Icons, Text } from 'folds';
|
||||
import React, { useCallback, useEffect, useState } from 'react';
|
||||
import { StageComponentProps } from './types';
|
||||
import { PhoneHit } from '../../styles/PhoneHit.css';
|
||||
|
||||
export function SSOStage({
|
||||
ssoRedirectURL,
|
||||
|
|
@ -57,7 +56,7 @@ export function SSOStage({
|
|||
<Box grow="Yes">
|
||||
<Text size="H4">SSO Login</Text>
|
||||
</Box>
|
||||
<IconButton className={PhoneHit} size="300" onClick={onCancel} radii="300">
|
||||
<IconButton size="300" onClick={onCancel} radii="300">
|
||||
<Icon src={Icons.Cross} />
|
||||
</IconButton>
|
||||
</Header>
|
||||
|
|
|
|||
|
|
@ -7,7 +7,6 @@ import { TUploadContent } from '../../utils/matrix';
|
|||
import { bytesToSize, getFileTypeIcon } from '../../utils/common';
|
||||
import { useMediaConfig } from '../../hooks/useMediaConfig';
|
||||
import { UploadFailureNote } from './UploadFailureNote';
|
||||
import { PhoneHitSpread28 } from '../../styles/PhoneHit.css';
|
||||
|
||||
type CompactUploadCardRendererProps = {
|
||||
isEncrypted?: boolean;
|
||||
|
|
@ -65,7 +64,6 @@ export function CompactUploadCardRenderer({
|
|||
</Chip>
|
||||
)}
|
||||
<IconButton
|
||||
className={PhoneHitSpread28}
|
||||
onClick={removeUpload}
|
||||
aria-label="Cancel Upload"
|
||||
variant="SurfaceVariant"
|
||||
|
|
|
|||
|
|
@ -13,7 +13,6 @@ import {
|
|||
import { useObjectURL } from '../../hooks/useObjectURL';
|
||||
import { useMediaConfig } from '../../hooks/useMediaConfig';
|
||||
import { UploadFailureNote } from './UploadFailureNote';
|
||||
import { PhoneHitSpread28 } from '../../styles/PhoneHit.css';
|
||||
|
||||
type PreviewImageProps = {
|
||||
fileItem: TUploadItem;
|
||||
|
|
@ -162,7 +161,6 @@ export function UploadCardRenderer({
|
|||
</Chip>
|
||||
)}
|
||||
<IconButton
|
||||
className={PhoneHitSpread28}
|
||||
onClick={removeUpload}
|
||||
aria-label="Cancel Upload"
|
||||
variant="SurfaceVariant"
|
||||
|
|
|
|||
|
|
@ -1,4 +1,3 @@
|
|||
import classNames from 'classnames';
|
||||
import React, { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { IPreviewUrlResponse } from 'matrix-js-sdk';
|
||||
import { Box, Icon, IconButton, Icons, Scroll, Spinner, Text, as, color, config } from 'folds';
|
||||
|
|
@ -11,7 +10,6 @@ import {
|
|||
useIntersectionObserver,
|
||||
} from '../../hooks/useIntersectionObserver';
|
||||
import * as css from './UrlPreviewCard.css';
|
||||
import { PhoneHitInPlace } from '../../styles/PhoneHit.css';
|
||||
import { tryDecodeURIComponent } from '../../utils/dom';
|
||||
import { mxcUrlToHttp } from '../../utils/matrix';
|
||||
import { useMediaAuthentication } from '../../hooks/useMediaAuthentication';
|
||||
|
|
@ -183,10 +181,7 @@ export const UrlPreviewHolder = as<'div'>(({ children, ...props }, ref) => {
|
|||
<>
|
||||
<div className={css.UrlPreviewHolderGradient({ position: 'Left' })} />
|
||||
<IconButton
|
||||
className={classNames(
|
||||
css.UrlPreviewHolderBtn({ position: 'Left' }),
|
||||
PhoneHitInPlace
|
||||
)}
|
||||
className={css.UrlPreviewHolderBtn({ position: 'Left' })}
|
||||
variant="Secondary"
|
||||
radii="Pill"
|
||||
size="300"
|
||||
|
|
@ -204,10 +199,7 @@ export const UrlPreviewHolder = as<'div'>(({ children, ...props }, ref) => {
|
|||
<>
|
||||
<div className={css.UrlPreviewHolderGradient({ position: 'Right' })} />
|
||||
<IconButton
|
||||
className={classNames(
|
||||
css.UrlPreviewHolderBtn({ position: 'Right' }),
|
||||
PhoneHitInPlace
|
||||
)}
|
||||
className={css.UrlPreviewHolderBtn({ position: 'Right' })}
|
||||
variant="Primary"
|
||||
radii="Pill"
|
||||
size="300"
|
||||
|
|
|
|||
|
|
@ -43,7 +43,6 @@ import { getPowerTagIconSrc, useGetMemberPowerTag } from '../../hooks/useMemberP
|
|||
import { useRoomCreators } from '../../hooks/useRoomCreators';
|
||||
import { useRoomPermissions } from '../../hooks/useRoomPermissions';
|
||||
import { useMemberPowerCompare } from '../../hooks/useMemberPowerCompare';
|
||||
import { PhoneHit } from '../../styles/PhoneHit.css';
|
||||
|
||||
type SelfDemoteAlertProps = {
|
||||
power: number;
|
||||
|
|
@ -71,7 +70,7 @@ function SelfDemoteAlert({ power, onCancel, onChange }: SelfDemoteAlertProps) {
|
|||
<Box grow="Yes">
|
||||
<Text size="H4">Self Demotion</Text>
|
||||
</Box>
|
||||
<IconButton className={PhoneHit} size="300" onClick={onCancel} radii="300">
|
||||
<IconButton size="300" onClick={onCancel} radii="300">
|
||||
<Icon src={Icons.Cross} />
|
||||
</IconButton>
|
||||
</Header>
|
||||
|
|
@ -121,7 +120,7 @@ function SharedPowerAlert({ power, onCancel, onChange }: SharedPowerAlertProps)
|
|||
<Box grow="Yes">
|
||||
<Text size="H4">Shared Power</Text>
|
||||
</Box>
|
||||
<IconButton className={PhoneHit} size="300" onClick={onCancel} radii="300">
|
||||
<IconButton size="300" onClick={onCancel} radii="300">
|
||||
<Icon src={Icons.Cross} />
|
||||
</IconButton>
|
||||
</Header>
|
||||
|
|
|
|||
|
|
@ -54,7 +54,6 @@ import { StateEvent } from '../../../types/matrix/room';
|
|||
import { getViaServers } from '../../plugins/via-servers';
|
||||
import { rateLimitedActions } from '../../utils/matrix';
|
||||
import { useAlive } from '../../hooks/useAlive';
|
||||
import { PhoneHit } from '../../styles/PhoneHit.css';
|
||||
|
||||
const SEARCH_OPTS: UseAsyncSearchOptions = {
|
||||
limit: 500,
|
||||
|
|
@ -202,7 +201,7 @@ export function AddExistingModal({ parentId, space, requestClose }: AddExistingM
|
|||
<Text size="H4">Add Existing</Text>
|
||||
</Box>
|
||||
<Box shrink="No">
|
||||
<IconButton className={PhoneHit} size="300" radii="300" onClick={requestClose}>
|
||||
<IconButton size="300" radii="300" onClick={requestClose}>
|
||||
<Icon src={Icons.Cross} />
|
||||
</IconButton>
|
||||
</Box>
|
||||
|
|
|
|||
|
|
@ -14,7 +14,8 @@ const captured = vi.hoisted(() => ({
|
|||
titles: [] as string[],
|
||||
}));
|
||||
|
||||
vi.mock('./shareController', () => ({
|
||||
vi.mock('./shareUpload', async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import('./shareUpload')>()),
|
||||
createShareController: (deps: {
|
||||
run: NonNullable<typeof captured.run>;
|
||||
maxBytes: NonNullable<typeof captured.maxBytes>;
|
||||
|
|
@ -30,9 +31,6 @@ vi.mock('./shareController', () => ({
|
|||
cancel: () => undefined,
|
||||
};
|
||||
},
|
||||
}));
|
||||
vi.mock('./shareSet', async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import('./shareSet')>()),
|
||||
sendShareSet: async (_port: unknown, into: string | { albumId: string; lastId: string }) => {
|
||||
captured.titles.push(typeof into === 'string' ? into : `into:${into.albumId}@${into.lastId}`);
|
||||
return { albumId: '$a', sent: 0, failed: [], failedAt: [] };
|
||||
|
|
|
|||
|
|
@ -3,7 +3,7 @@ import { renderToStaticMarkup } from 'react-dom/server';
|
|||
import { describe, expect, it } from 'vitest';
|
||||
import { ClientConfigProvider } from '../../hooks/useClientConfig';
|
||||
import type { ClientConfig } from '../../hooks/useClientConfig';
|
||||
import { ShareState } from './shareController';
|
||||
import { ShareState } from './shareUpload';
|
||||
import { ShareSetView, shareEnabled, useShareEnabled } from './ShareSet';
|
||||
|
||||
const text = (html: string) =>
|
||||
|
|
|
|||
|
|
@ -9,9 +9,17 @@ import { uploadContent } from '../../utils/matrix';
|
|||
import { safeFile } from '../../utils/mimeTypes';
|
||||
import { getMsgContent } from '../room/msgContent';
|
||||
import { FILE_HASH_KEY, hashForSend } from './fileReceipt';
|
||||
import { ShareController, ShareState, createShareController } from './shareController';
|
||||
import { titleIn } from './albumFolders';
|
||||
import { DEFAULT_TITLE, ExistingAlbum, freshest, sendShareSet, ThreadEvent } from './shareSet';
|
||||
import {
|
||||
DEFAULT_TITLE,
|
||||
ExistingAlbum,
|
||||
ShareController,
|
||||
ShareState,
|
||||
ThreadEvent,
|
||||
createShareController,
|
||||
freshest,
|
||||
sendShareSet,
|
||||
} from './shareUpload';
|
||||
import * as css from './AlbumView.css';
|
||||
|
||||
/** Off unless `fileZoneShare.enabled` is true. An encrypted zone is never offered the share. */
|
||||
|
|
|
|||
|
|
@ -2,7 +2,7 @@ import { describe, expect, it } from 'vitest';
|
|||
import { buildAlbums } from './buildAlbums';
|
||||
import type { Album, ZoneEvent } from './buildAlbums';
|
||||
import { folderOf, listFolder, splitPath, titleIn } from './albumFolders';
|
||||
import { DEFAULT_TITLE, sendShareSet } from './shareSet';
|
||||
import { DEFAULT_TITLE, sendShareSet } from './shareUpload';
|
||||
|
||||
const album = (id: string, title: string, ts = 1): Album => ({
|
||||
id,
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
import { describe, expect, it } from 'vitest';
|
||||
import { AlbumInput, ZoneEvent, buildAlbums, lastEvent } from './buildAlbums';
|
||||
import { AlbumInput, ZoneEvent, buildAlbums, isFileZone, lastEvent, zoneView } from './buildAlbums';
|
||||
|
||||
const root = (id: string, ts: number, over: Partial<ZoneEvent> = {}): ZoneEvent => ({
|
||||
event_id: id,
|
||||
|
|
@ -334,3 +334,38 @@ describe('Mind receipts', () => {
|
|||
expect(a.count).toBe(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('zoneView', () => {
|
||||
it('opens albums by default and the timeline for an event deep link', () => {
|
||||
expect(zoneView(undefined, undefined)).toBe('albums');
|
||||
expect(zoneView(undefined, '$e')).toBe('timeline');
|
||||
});
|
||||
it('lets an event link win over an earlier choice of albums', () => {
|
||||
expect(zoneView('albums', '$e')).toBe('timeline');
|
||||
});
|
||||
it('honours the choice when there is no event link', () => {
|
||||
expect(zoneView('albums', undefined)).toBe('albums');
|
||||
expect(zoneView('timeline', undefined)).toBe('timeline');
|
||||
});
|
||||
});
|
||||
|
||||
describe('isFileZone', () => {
|
||||
const room = { roomId: '!f:x', aliases: ['#files:x'] };
|
||||
it('is true for the file-zone create type', () => {
|
||||
expect(isFileZone({ ...room, createType: 'org.gamecult.file_zone' }, {})).toBe(true);
|
||||
});
|
||||
it('is false for other create types and for plain rooms', () => {
|
||||
expect(isFileZone({ ...room, createType: 'm.space' }, {})).toBe(false);
|
||||
expect(isFileZone({ ...room, createType: 'org.gamecult.other' }, {})).toBe(false);
|
||||
expect(isFileZone({ ...room, createType: 'org.gamecult.file_zone.x' }, {})).toBe(false);
|
||||
expect(isFileZone(room, {})).toBe(false);
|
||||
expect(isFileZone(room, { fileZoneRooms: [] })).toBe(false);
|
||||
});
|
||||
it('is true when the room id or an alias is configured', () => {
|
||||
expect(isFileZone(room, { fileZoneRooms: ['!f:x'] })).toBe(true);
|
||||
expect(isFileZone(room, { fileZoneRooms: ['#other:x', '#files:x'] })).toBe(true);
|
||||
});
|
||||
it('is false when only another room is configured', () => {
|
||||
expect(isFileZone(room, { fileZoneRooms: ['!g:x', '#g:x'] })).toBe(false);
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -179,6 +179,27 @@ export const looseNote = (files: AlbumFile[]): string => {
|
|||
/** Where the album view stands when it decides whether to show the loose-files note. */
|
||||
export type ViewState = { open: boolean; encrypted: boolean; loading: boolean; error: boolean };
|
||||
|
||||
export type ZoneView = 'albums' | 'timeline';
|
||||
|
||||
/** The view a file-zone room shows. A link to an event always wins; else the user's choice; else albums. */
|
||||
export const zoneView = (choice: ZoneView | undefined, eventId: string | undefined): ZoneView =>
|
||||
eventId ? 'timeline' : choice ?? 'albums';
|
||||
|
||||
export const FILE_ZONE_TYPE = 'org.gamecult.file_zone';
|
||||
|
||||
export type FileZoneRoom = {
|
||||
roomId: string;
|
||||
/** Canonical and alternative aliases. */
|
||||
aliases?: string[];
|
||||
/** The `type` of the room's m.room.create content. */
|
||||
createType?: string;
|
||||
};
|
||||
|
||||
/** A room is the file zone when its create type says so or the client config lists it. */
|
||||
export const isFileZone = (room: FileZoneRoom, config: { fileZoneRooms?: string[] }): boolean =>
|
||||
room.createType === FILE_ZONE_TYPE ||
|
||||
!!config.fileZoneRooms?.some((r) => r === room.roomId || room.aliases?.includes(r));
|
||||
|
||||
/** The note for the list view only: never inside an open album, an encrypted zone, or a load that is not finished. */
|
||||
export const looseNoteFor = (files: AlbumFile[], view: ViewState): string =>
|
||||
view.open || view.encrypted || view.loading || view.error ? '' : looseNote(files);
|
||||
|
|
|
|||
|
|
@ -1,24 +0,0 @@
|
|||
import { describe, expect, it } from 'vitest';
|
||||
import { isFileZone } from './isFileZone';
|
||||
|
||||
const room = { roomId: '!f:x', aliases: ['#files:x'] };
|
||||
|
||||
describe('isFileZone', () => {
|
||||
it('is true for the file-zone create type', () => {
|
||||
expect(isFileZone({ ...room, createType: 'org.gamecult.file_zone' }, {})).toBe(true);
|
||||
});
|
||||
it('is false for other create types and for plain rooms', () => {
|
||||
expect(isFileZone({ ...room, createType: 'm.space' }, {})).toBe(false);
|
||||
expect(isFileZone({ ...room, createType: 'org.gamecult.other' }, {})).toBe(false);
|
||||
expect(isFileZone({ ...room, createType: 'org.gamecult.file_zone.x' }, {})).toBe(false);
|
||||
expect(isFileZone(room, {})).toBe(false);
|
||||
expect(isFileZone(room, { fileZoneRooms: [] })).toBe(false);
|
||||
});
|
||||
it('is true when the room id or an alias is configured', () => {
|
||||
expect(isFileZone(room, { fileZoneRooms: ['!f:x'] })).toBe(true);
|
||||
expect(isFileZone(room, { fileZoneRooms: ['#other:x', '#files:x'] })).toBe(true);
|
||||
});
|
||||
it('is false when only another room is configured', () => {
|
||||
expect(isFileZone(room, { fileZoneRooms: ['!g:x', '#g:x'] })).toBe(false);
|
||||
});
|
||||
});
|
||||
|
|
@ -1,14 +0,0 @@
|
|||
export const FILE_ZONE_TYPE = 'org.gamecult.file_zone';
|
||||
|
||||
export type FileZoneRoom = {
|
||||
roomId: string;
|
||||
/** Canonical and alternative aliases. */
|
||||
aliases?: string[];
|
||||
/** The `type` of the room's m.room.create content. */
|
||||
createType?: string;
|
||||
};
|
||||
|
||||
/** A room is the file zone when its create type says so or the client config lists it. */
|
||||
export const isFileZone = (room: FileZoneRoom, config: { fileZoneRooms?: string[] }): boolean =>
|
||||
room.createType === FILE_ZONE_TYPE ||
|
||||
!!config.fileZoneRooms?.some((r) => r === room.roomId || room.aliases?.includes(r));
|
||||
|
|
@ -1,29 +0,0 @@
|
|||
import { describe, expect, it } from 'vitest';
|
||||
import { mapLimit } from './mapLimit';
|
||||
|
||||
describe('mapLimit', () => {
|
||||
it('keeps result order and never exceeds the limit', async () => {
|
||||
let inFlight = 0;
|
||||
let peak = 0;
|
||||
const out = await mapLimit([5, 1, 4, 2, 3, 0], 2, async (n) => {
|
||||
inFlight += 1;
|
||||
peak = Math.max(peak, inFlight);
|
||||
await new Promise((r) => {
|
||||
setTimeout(r, n);
|
||||
});
|
||||
inFlight -= 1;
|
||||
return n * 10;
|
||||
});
|
||||
expect(out).toEqual([50, 10, 40, 20, 30, 0]);
|
||||
expect(peak).toBe(2);
|
||||
});
|
||||
it('handles an empty list and rejects when a call rejects', async () => {
|
||||
expect(await mapLimit([], 3, async (n) => n)).toEqual([]);
|
||||
await expect(
|
||||
mapLimit([1, 2], 2, async (n) => {
|
||||
if (n === 2) throw new Error('boom');
|
||||
return n;
|
||||
})
|
||||
).rejects.toThrow('boom');
|
||||
});
|
||||
});
|
||||
|
|
@ -1,19 +0,0 @@
|
|||
/** Like Promise.all(items.map(fn)) but with at most `limit` calls in flight; result order kept. */
|
||||
export const mapLimit = async <T, R>(
|
||||
items: T[],
|
||||
limit: number,
|
||||
fn: (item: T) => Promise<R>
|
||||
): Promise<R[]> => {
|
||||
const out = new Array<R>(items.length);
|
||||
let next = 0;
|
||||
const worker = async () => {
|
||||
while (next < items.length) {
|
||||
const i = next;
|
||||
next += 1;
|
||||
// eslint-disable-next-line no-await-in-loop
|
||||
out[i] = await fn(items[i]);
|
||||
}
|
||||
};
|
||||
await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));
|
||||
return out;
|
||||
};
|
||||
|
|
@ -1,27 +0,0 @@
|
|||
/** One page of a Matrix paginated endpoint: its events and the token for the next page, if any. */
|
||||
export type Page<T> = { chunk?: T[]; next_batch?: string };
|
||||
|
||||
/** Pages read per endpoint at most, so a runaway zone cannot hold the phone in a loop. */
|
||||
export const MAX_PAGES = 20;
|
||||
|
||||
/**
|
||||
* Reads every page of an endpoint by following `next_batch`, up to `maxPages`. `truncated` is true
|
||||
* when the cap stopped the read with more still to come, so a caller can say the list is partial.
|
||||
*/
|
||||
export const readPages = async <T>(
|
||||
fetchPage: (from: string | undefined) => Promise<Page<T>>,
|
||||
maxPages = MAX_PAGES
|
||||
): Promise<{ items: T[]; truncated: boolean }> => {
|
||||
const items: T[] = [];
|
||||
let from: string | undefined;
|
||||
for (let n = 0; n < maxPages; n += 1) {
|
||||
// eslint-disable-next-line no-await-in-loop
|
||||
const page = await fetchPage(from);
|
||||
items.push(...(page.chunk ?? []));
|
||||
// An empty page ends the read even if a token is returned: a server that keeps handing out
|
||||
// tokens with nothing behind them would otherwise spend every page of the cap.
|
||||
if (!page.next_batch || !page.chunk?.length) return { items, truncated: false };
|
||||
from = page.next_batch;
|
||||
}
|
||||
return { items, truncated: true };
|
||||
};
|
||||
|
|
@ -1,135 +0,0 @@
|
|||
// The share panel's state machine, apart from React and Matrix: what is picked, what phase the
|
||||
// send is in, and the rules that keep a room to one send at a time. ShareSet.tsx draws it.
|
||||
import { ShareResult, remainingAfter, resultNote } from './shareSet';
|
||||
|
||||
export type Picked = { name: string; type: string; size?: number };
|
||||
|
||||
export type SharePhase =
|
||||
| { kind: 'idle' }
|
||||
| { kind: 'sending'; done: number }
|
||||
| { kind: 'done'; text: string };
|
||||
|
||||
export type ShareState<F extends Picked> = {
|
||||
files: F[];
|
||||
title: string;
|
||||
phase: SharePhase;
|
||||
/** Bumps whenever the pick is emptied, so the file input can be remounted and re-pick the same files. */
|
||||
epoch: number;
|
||||
};
|
||||
|
||||
export const ENCRYPTED_NOTE = 'Not shared: this room is encrypted.';
|
||||
|
||||
const MIB = 1024 * 1024;
|
||||
|
||||
/**
|
||||
* Files the homeserver would refuse for size (its `m.upload.size`, which Synapse enforces as a
|
||||
* limit, so a file of exactly that size goes), split from the rest before anything is sent. A
|
||||
* missing cap or size refuses nothing.
|
||||
*/
|
||||
export const splitBySize = <F extends Picked>(files: F[], cap: number | undefined) => {
|
||||
const over = (f: F) => cap !== undefined && f.size !== undefined && f.size > cap;
|
||||
return { sendable: files.filter((f) => !over(f)), tooLarge: files.filter(over) };
|
||||
};
|
||||
|
||||
const tooLargeNote = (names: string[], cap: number): string =>
|
||||
`Too large for this server (limit ${Math.round((cap / MIB) * 10) / 10} MB): ${names.join(', ')}`;
|
||||
|
||||
export type ShareDeps<F extends Picked> = {
|
||||
roomId: string;
|
||||
isEncrypted: () => boolean;
|
||||
/** Sends the files as one album; reports each settled file through onFile. */
|
||||
run: (files: F[], title: string, onFile: () => void, signal: AbortSignal) => Promise<ShareResult>;
|
||||
/** The homeserver's upload cap in bytes (`m.upload.size`), when it states one. */
|
||||
maxBytes?: () => number | undefined;
|
||||
/** Called after a send that reached the room, whatever it left unsent. */
|
||||
onSent?: () => void;
|
||||
};
|
||||
|
||||
/** Rooms with a share in flight. Module-level: leaving the page unmounts the panel, not the send. */
|
||||
const sending = new Set<string>();
|
||||
|
||||
export const createShareController = <F extends Picked>(deps: ShareDeps<F>) => {
|
||||
let state: ShareState<F> = { files: [], title: '', phase: { kind: 'idle' }, epoch: 0 };
|
||||
const listeners = new Set<() => void>();
|
||||
let running: AbortController | undefined;
|
||||
const set = (patch: Partial<ShareState<F>>) => {
|
||||
state = { ...state, ...patch };
|
||||
listeners.forEach((l) => l());
|
||||
};
|
||||
|
||||
const clear = () => set({ files: [], title: '', epoch: state.epoch + 1 });
|
||||
|
||||
const send = async () => {
|
||||
if (sending.has(deps.roomId) || state.files.length === 0) return;
|
||||
if (deps.isEncrypted()) {
|
||||
set({ phase: { kind: 'done', text: ENCRYPTED_NOTE } });
|
||||
return;
|
||||
}
|
||||
// Files over the cap are named and dropped from the pick before any upload or album root: a
|
||||
// retry cannot help them, and a root with nothing under it is a lone message nobody lists.
|
||||
const cap = deps.maxBytes?.();
|
||||
const { sendable, tooLarge } = splitBySize(state.files, cap);
|
||||
const sizeNote = tooLarge.length
|
||||
? tooLargeNote(
|
||||
tooLarge.map((f) => f.name),
|
||||
cap as number
|
||||
)
|
||||
: '';
|
||||
if (sendable.length === 0) {
|
||||
const phase: SharePhase = { kind: 'done', text: `Nothing was shared. ${sizeNote}` };
|
||||
set({ files: [], title: '', epoch: state.epoch + 1, phase });
|
||||
return;
|
||||
}
|
||||
sending.add(deps.roomId);
|
||||
const abort = new AbortController();
|
||||
running = abort;
|
||||
const { title } = state;
|
||||
const files = sendable;
|
||||
set({ files, phase: { kind: 'sending', done: 0 } });
|
||||
let settled = 0;
|
||||
try {
|
||||
const res = await deps.run(
|
||||
files,
|
||||
title,
|
||||
() => {
|
||||
settled += 1;
|
||||
set({ phase: { kind: 'sending', done: settled } });
|
||||
},
|
||||
abort.signal
|
||||
);
|
||||
deps.onSent?.();
|
||||
const left = remainingAfter(files, res);
|
||||
const phase: SharePhase = {
|
||||
kind: 'done',
|
||||
text: sizeNote ? `${resultNote(res)} ${sizeNote}` : resultNote(res),
|
||||
};
|
||||
// One notification: no state is ever drawn with the pick emptied and the send still running.
|
||||
if (left.length === 0) set({ files: [], title: '', epoch: state.epoch + 1, phase });
|
||||
else set({ files: left, phase });
|
||||
} catch (e: any) {
|
||||
const failure = `Could not share: ${e?.message ?? 'send failed'}`;
|
||||
set({ phase: { kind: 'done', text: sizeNote ? `${failure}. ${sizeNote}` : failure } });
|
||||
} finally {
|
||||
running = undefined;
|
||||
sending.delete(deps.roomId);
|
||||
}
|
||||
};
|
||||
|
||||
return {
|
||||
getState: () => state,
|
||||
subscribe: (l: () => void) => {
|
||||
listeners.add(l);
|
||||
return () => {
|
||||
listeners.delete(l);
|
||||
};
|
||||
},
|
||||
pick: (files: F[]) => set({ files, phase: { kind: 'idle' } }),
|
||||
setTitle: (title: string) => set({ title }),
|
||||
cancel: clear,
|
||||
/** Stops a send in flight: the running upload is aborted and the rest are left picked. */
|
||||
stop: () => running?.abort(),
|
||||
send,
|
||||
};
|
||||
};
|
||||
|
||||
export type ShareController<F extends Picked> = ReturnType<typeof createShareController<F>>;
|
||||
|
|
@ -1,328 +0,0 @@
|
|||
import { describe, expect, it } from 'vitest';
|
||||
import config from '../../../../config.json';
|
||||
import { ZoneEvent, buildAlbums } from './buildAlbums';
|
||||
import {
|
||||
DEFAULT_TITLE,
|
||||
ShareFile,
|
||||
SharePort,
|
||||
CANCELLED,
|
||||
freshest,
|
||||
refusalOf,
|
||||
remainingAfter,
|
||||
resultNote,
|
||||
sendShareSet,
|
||||
threadRelation,
|
||||
} from './shareSet';
|
||||
|
||||
const kindOf = (f: ShareFile) => (f.mimeType.startsWith('audio') ? 'm.audio' : 'm.file');
|
||||
|
||||
/** A fake room: records what is sent, as the events Synapse would return from /relations. */
|
||||
const room = (failOn: string[] = []) => {
|
||||
const events: ZoneEvent[] = [];
|
||||
const port: SharePort<ShareFile> = {
|
||||
send: async (content) => {
|
||||
const id = `$e${events.length + 1}`;
|
||||
events.push({
|
||||
event_id: id,
|
||||
type: 'm.room.message',
|
||||
sender: '@aqua:chat.gamecult.org',
|
||||
origin_server_ts: 1000 + events.length,
|
||||
content,
|
||||
});
|
||||
return id;
|
||||
},
|
||||
contentOf: async (f) => {
|
||||
if (failOn.includes(f.name)) throw new Error('upload failed');
|
||||
return {
|
||||
msgtype: kindOf(f),
|
||||
body: f.name,
|
||||
filename: f.name,
|
||||
url: `mxc://x/${f.name}`,
|
||||
info: { mimetype: f.mimeType },
|
||||
};
|
||||
},
|
||||
};
|
||||
const album = () => {
|
||||
const [root, ...replies] = events;
|
||||
return buildAlbums([{ root, replies }], 'chat.gamecult.org')[0];
|
||||
};
|
||||
return { events, port, album };
|
||||
};
|
||||
|
||||
const clips: ShareFile[] = [
|
||||
{ name: 'a.ogg', mimeType: 'audio/ogg' },
|
||||
{ name: 'b.ogg', mimeType: 'audio/ogg' },
|
||||
{ name: 'c.txt', mimeType: 'text/plain' },
|
||||
];
|
||||
|
||||
describe('sendShareSet', () => {
|
||||
it('reads back as one album of the files in pick order', async () => {
|
||||
const r = room();
|
||||
const res = await sendShareSet(r.port, 'Take 4', clips);
|
||||
expect(res).toEqual({ albumId: '$e1', sent: 3, failed: [], failedAt: [], reasons: [] });
|
||||
const album = r.album();
|
||||
expect(album.title).toBe('Take 4');
|
||||
expect(album.files.map((f) => [f.name, f.kind])).toEqual([
|
||||
['a.ogg', 'audio'],
|
||||
['b.ogg', 'audio'],
|
||||
['c.txt', 'file'],
|
||||
]);
|
||||
});
|
||||
|
||||
it('threads every file under the root, each falling back to the previous event', async () => {
|
||||
const r = room();
|
||||
await sendShareSet(r.port, 't', clips);
|
||||
const rels = r.events.slice(1).map((e) => e.content?.['m.relates_to']);
|
||||
expect(rels).toEqual([
|
||||
threadRelation('$e1', '$e1'),
|
||||
threadRelation('$e1', '$e2'),
|
||||
threadRelation('$e1', '$e3'),
|
||||
]);
|
||||
expect(r.events[0].content?.['m.relates_to']).toBeUndefined();
|
||||
});
|
||||
|
||||
it('titles an untitled share', async () => {
|
||||
const r = room();
|
||||
await sendShareSet(r.port, ' ', clips.slice(0, 1));
|
||||
expect(r.album().title).toBe(DEFAULT_TITLE);
|
||||
});
|
||||
|
||||
it('names a failed file and still sends the rest', async () => {
|
||||
const r = room(['b.ogg']);
|
||||
const res = await sendShareSet(r.port, 't', clips);
|
||||
expect(res.failed).toEqual(['b.ogg']);
|
||||
expect(res.sent).toBe(2);
|
||||
expect(r.album().files.map((f) => f.name)).toEqual(['a.ogg', 'c.txt']);
|
||||
// the next file falls back to the last event that exists, not to the failed one
|
||||
expect(r.events[2].content?.['m.relates_to']).toEqual(threadRelation('$e1', '$e2'));
|
||||
});
|
||||
|
||||
it('throws when the root cannot be sent, uploading nothing', async () => {
|
||||
let uploads = 0;
|
||||
const port: SharePort<ShareFile> = {
|
||||
send: async () => {
|
||||
throw new Error('M_FORBIDDEN');
|
||||
},
|
||||
contentOf: async () => {
|
||||
uploads += 1;
|
||||
return {};
|
||||
},
|
||||
};
|
||||
await expect(sendShareSet(port, 't', clips)).rejects.toThrow('M_FORBIDDEN');
|
||||
expect(uploads).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('the share flag', () => {
|
||||
it('ships off', () => {
|
||||
expect(config.fileZoneShare).toEqual({ enabled: false });
|
||||
});
|
||||
});
|
||||
|
||||
describe('after a send', () => {
|
||||
it('keeps the failed one of two same-named files, not both', async () => {
|
||||
const twins: ShareFile[] = [
|
||||
{ name: 'a.ogg', mimeType: 'audio/ogg' },
|
||||
{ name: 'a.ogg', mimeType: 'audio/ogg' },
|
||||
];
|
||||
let n = 0;
|
||||
const r = room();
|
||||
const port: SharePort<ShareFile> = {
|
||||
...r.port,
|
||||
contentOf: async (f) => {
|
||||
n += 1;
|
||||
if (n === 2) throw new Error('second upload failed');
|
||||
return r.port.contentOf(f);
|
||||
},
|
||||
};
|
||||
const res = await sendShareSet(port, 't', twins);
|
||||
expect(res.failedAt).toEqual([1]);
|
||||
expect(remainingAfter(twins, res)).toEqual([twins[1]]);
|
||||
});
|
||||
|
||||
it('keeps only the failed files picked, so a retry is one tap', async () => {
|
||||
const r = room(['b.ogg']);
|
||||
const res = await sendShareSet(r.port, 't', clips);
|
||||
expect(remainingAfter(clips, res).map((f) => f.name)).toEqual(['b.ogg']);
|
||||
expect(resultNote(res)).toBe('Shared 2. Not sent: b.ogg');
|
||||
});
|
||||
|
||||
it('keeps everything and says nothing was shared when every upload failed', async () => {
|
||||
const r = room(clips.map((c) => c.name));
|
||||
const res = await sendShareSet(r.port, 't', clips);
|
||||
expect(remainingAfter(clips, res)).toEqual(clips);
|
||||
expect(resultNote(res)).toBe('Nothing was shared. Not sent: a.ogg, b.ogg, c.txt');
|
||||
});
|
||||
|
||||
it('clears the pick on full success', async () => {
|
||||
const r = room();
|
||||
const res = await sendShareSet(r.port, 't', clips);
|
||||
expect(remainingAfter(clips, res)).toEqual([]);
|
||||
expect(resultNote(res)).toBe('Shared 3 files.');
|
||||
});
|
||||
});
|
||||
|
||||
describe('adding to an existing album', () => {
|
||||
it('sends no root; each file threads under the album, the first after `lastId`', async () => {
|
||||
const r = room();
|
||||
const sent: Record<string, unknown>[] = [];
|
||||
const port = {
|
||||
...r.port,
|
||||
send: async (c: Record<string, unknown>) => {
|
||||
sent.push(c);
|
||||
return `$n${sent.length}`;
|
||||
},
|
||||
};
|
||||
const res = await sendShareSet(
|
||||
port,
|
||||
{ albumId: '$root', lastId: '$last', lastTs: 1 },
|
||||
clips.slice(0, 2)
|
||||
);
|
||||
expect(res.albumId).toBe('$root');
|
||||
expect(res.sent).toBe(2);
|
||||
expect(sent.map((c) => c.msgtype)).toEqual(['m.audio', 'm.audio']);
|
||||
expect(sent.map((c) => c['m.relates_to'])).toEqual([
|
||||
threadRelation('$root', '$last'),
|
||||
threadRelation('$root', '$n1'),
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('refusals', () => {
|
||||
const refuse = (errcode: string): SharePort<ShareFile> => ({
|
||||
send: async () => '$e',
|
||||
contentOf: async () => {
|
||||
throw Object.assign(new Error('raw server text'), { errcode });
|
||||
},
|
||||
});
|
||||
|
||||
it('names the three upload refusals and nothing else', () => {
|
||||
expect(refusalOf({ errcode: 'M_TOO_LARGE' })).toBe('too large for this server');
|
||||
expect(refusalOf({ errcode: 'M_FORBIDDEN' })).toBe('not allowed to upload here');
|
||||
expect(refusalOf({ errcode: 'M_LIMIT_EXCEEDED' })).toBe(
|
||||
'uploading too fast, try again shortly'
|
||||
);
|
||||
expect(refusalOf({ errcode: 'M_UNKNOWN' })).toBeUndefined();
|
||||
expect(refusalOf({ errcode: 'constructor' })).toBeUndefined();
|
||||
expect(refusalOf(new Error('x'))).toBeUndefined();
|
||||
expect(refusalOf(null)).toBeUndefined();
|
||||
});
|
||||
|
||||
it('the note carries the reason beside each refused file', async () => {
|
||||
const res = await sendShareSet(refuse('M_TOO_LARGE'), 't', clips.slice(0, 2));
|
||||
expect(resultNote(res)).toBe(
|
||||
'Nothing was shared. Not sent: a.ogg (too large for this server), b.ogg (too large for this server)'
|
||||
);
|
||||
});
|
||||
|
||||
it('a failure the client saw, not the server, is named too', async () => {
|
||||
const dropped: SharePort<ShareFile> = {
|
||||
send: async () => '$e',
|
||||
contentOf: async () => {
|
||||
throw Object.assign(new Error('x'), {
|
||||
errcode: 'AbortError',
|
||||
info: { aborted: true, progressed: true },
|
||||
});
|
||||
},
|
||||
};
|
||||
const res = await sendShareSet(dropped, 't', clips.slice(0, 1));
|
||||
expect(resultNote(res)).toBe(
|
||||
'Nothing was shared. Not sent: a.ogg (the connection dropped partway through)'
|
||||
);
|
||||
});
|
||||
|
||||
it('an unnamed failure lists the bare name', async () => {
|
||||
const res = await sendShareSet(refuse('M_UNKNOWN'), 't', clips.slice(0, 1));
|
||||
expect(resultNote(res)).toBe('Nothing was shared. Not sent: a.ogg');
|
||||
});
|
||||
});
|
||||
|
||||
describe('stopping a send', () => {
|
||||
/** A port whose upload of `stopAt` aborts the signal as it runs, as the Stop button does mid-upload. */
|
||||
const stopping = (stopAt: string, abortAfterUpload = false) => {
|
||||
const ac = new AbortController();
|
||||
const r = room();
|
||||
const port: SharePort<ShareFile> = {
|
||||
...r.port,
|
||||
signal: ac.signal,
|
||||
contentOf: async (f) => {
|
||||
if (f.name !== stopAt) return r.port.contentOf(f);
|
||||
ac.abort();
|
||||
if (abortAfterUpload) return r.port.contentOf(f);
|
||||
throw Object.assign(new Error('aborted'), { name: 'AbortError' });
|
||||
},
|
||||
};
|
||||
return { port, r };
|
||||
};
|
||||
|
||||
it('an upload aborted mid-file leaves that file and the rest unsent, named as stopped', async () => {
|
||||
const { port, r } = stopping('b.ogg');
|
||||
const res = await sendShareSet(port, 't', clips);
|
||||
expect(res.sent).toBe(1);
|
||||
expect(res.failed).toEqual(['b.ogg', 'c.txt']);
|
||||
expect(res.failedAt).toEqual([1, 2]);
|
||||
expect(res.reasons).toEqual([CANCELLED, CANCELLED]);
|
||||
expect(r.album().files.map((f) => f.name)).toEqual(['a.ogg']);
|
||||
expect(remainingAfter(clips, res).map((f) => f.name)).toEqual(['b.ogg', 'c.txt']);
|
||||
expect(resultNote(res)).toBe('Shared 1. Not sent: b.ogg (stopped), c.txt (stopped)');
|
||||
});
|
||||
|
||||
it('a file whose upload finished after the stop is not sent', async () => {
|
||||
const { port, r } = stopping('b.ogg', true);
|
||||
const res = await sendShareSet(port, 't', clips);
|
||||
expect(res.sent).toBe(1);
|
||||
expect(res.failedAt).toEqual([1, 2]);
|
||||
expect(r.album().files.map((f) => f.name)).toEqual(['a.ogg']);
|
||||
});
|
||||
|
||||
it('a signal already aborted starts nothing and sends everything back as unsent', async () => {
|
||||
const r = room();
|
||||
const ac = new AbortController();
|
||||
ac.abort();
|
||||
let uploads = 0;
|
||||
const res = await sendShareSet(
|
||||
{
|
||||
...r.port,
|
||||
signal: ac.signal,
|
||||
contentOf: async (f) => {
|
||||
uploads += 1;
|
||||
return r.port.contentOf(f);
|
||||
},
|
||||
},
|
||||
{ albumId: '$a', lastId: '$l', lastTs: 1 },
|
||||
clips
|
||||
);
|
||||
expect(uploads).toBe(0);
|
||||
expect(res.sent).toBe(0);
|
||||
expect(res.failedAt).toEqual([0, 1, 2]);
|
||||
expect(r.events).toEqual([]);
|
||||
});
|
||||
|
||||
it('an abort that is not a stop is an ordinary failure', async () => {
|
||||
const r = room(['b.ogg']);
|
||||
const res = await sendShareSet({ ...r.port, signal: new AbortController().signal }, 't', clips);
|
||||
expect(res.failedAt).toEqual([1]);
|
||||
expect(res.reasons).toEqual([undefined]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('freshest', () => {
|
||||
const album = { albumId: '$alb', lastId: '$old', lastTs: 100 };
|
||||
it('moves lastId to a newer event of the same thread', () => {
|
||||
expect(
|
||||
freshest(album, [
|
||||
{ id: '$mid', ts: 150, threadRoot: '$alb' },
|
||||
{ id: '$new', ts: 200, threadRoot: '$alb' },
|
||||
])
|
||||
).toEqual({ albumId: '$alb', lastId: '$new', lastTs: 200 });
|
||||
});
|
||||
it('ignores older events and events of other threads or none', () => {
|
||||
expect(
|
||||
freshest(album, [
|
||||
{ id: '$older', ts: 50, threadRoot: '$alb' },
|
||||
{ id: '$other', ts: 900, threadRoot: '$else' },
|
||||
{ id: '$loose', ts: 900 },
|
||||
])
|
||||
).toEqual(album);
|
||||
});
|
||||
});
|
||||
|
|
@ -1,6 +1,328 @@
|
|||
import { describe, expect, it } from 'vitest';
|
||||
import { Picked, ShareDeps, createShareController } from './shareController';
|
||||
import { ShareResult } from './shareSet';
|
||||
import { ZoneEvent, buildAlbums } from './buildAlbums';
|
||||
import {
|
||||
DEFAULT_TITLE,
|
||||
ShareFile,
|
||||
SharePort,
|
||||
CANCELLED,
|
||||
freshest,
|
||||
refusalOf,
|
||||
remainingAfter,
|
||||
resultNote,
|
||||
sendShareSet,
|
||||
Picked,
|
||||
ShareDeps,
|
||||
ShareResult,
|
||||
createShareController,
|
||||
threadRelation,
|
||||
} from './shareUpload';
|
||||
|
||||
const kindOf = (f: ShareFile) => (f.mimeType.startsWith('audio') ? 'm.audio' : 'm.file');
|
||||
|
||||
/** A fake room: records what is sent, as the events Synapse would return from /relations. */
|
||||
const room = (failOn: string[] = []) => {
|
||||
const events: ZoneEvent[] = [];
|
||||
const port: SharePort<ShareFile> = {
|
||||
send: async (content) => {
|
||||
const id = `$e${events.length + 1}`;
|
||||
events.push({
|
||||
event_id: id,
|
||||
type: 'm.room.message',
|
||||
sender: '@aqua:chat.gamecult.org',
|
||||
origin_server_ts: 1000 + events.length,
|
||||
content,
|
||||
});
|
||||
return id;
|
||||
},
|
||||
contentOf: async (f) => {
|
||||
if (failOn.includes(f.name)) throw new Error('upload failed');
|
||||
return {
|
||||
msgtype: kindOf(f),
|
||||
body: f.name,
|
||||
filename: f.name,
|
||||
url: `mxc://x/${f.name}`,
|
||||
info: { mimetype: f.mimeType },
|
||||
};
|
||||
},
|
||||
};
|
||||
const album = () => {
|
||||
const [root, ...replies] = events;
|
||||
return buildAlbums([{ root, replies }], 'chat.gamecult.org')[0];
|
||||
};
|
||||
return { events, port, album };
|
||||
};
|
||||
|
||||
const clips: ShareFile[] = [
|
||||
{ name: 'a.ogg', mimeType: 'audio/ogg' },
|
||||
{ name: 'b.ogg', mimeType: 'audio/ogg' },
|
||||
{ name: 'c.txt', mimeType: 'text/plain' },
|
||||
];
|
||||
|
||||
describe('sendShareSet', () => {
|
||||
it('reads back as one album of the files in pick order', async () => {
|
||||
const r = room();
|
||||
const res = await sendShareSet(r.port, 'Take 4', clips);
|
||||
expect(res).toEqual({ albumId: '$e1', sent: 3, failed: [], failedAt: [], reasons: [] });
|
||||
const album = r.album();
|
||||
expect(album.title).toBe('Take 4');
|
||||
expect(album.files.map((f) => [f.name, f.kind])).toEqual([
|
||||
['a.ogg', 'audio'],
|
||||
['b.ogg', 'audio'],
|
||||
['c.txt', 'file'],
|
||||
]);
|
||||
});
|
||||
|
||||
it('threads every file under the root, each falling back to the previous event', async () => {
|
||||
const r = room();
|
||||
await sendShareSet(r.port, 't', clips);
|
||||
const rels = r.events.slice(1).map((e) => e.content?.['m.relates_to']);
|
||||
expect(rels).toEqual([
|
||||
threadRelation('$e1', '$e1'),
|
||||
threadRelation('$e1', '$e2'),
|
||||
threadRelation('$e1', '$e3'),
|
||||
]);
|
||||
expect(r.events[0].content?.['m.relates_to']).toBeUndefined();
|
||||
});
|
||||
|
||||
it('titles an untitled share', async () => {
|
||||
const r = room();
|
||||
await sendShareSet(r.port, ' ', clips.slice(0, 1));
|
||||
expect(r.album().title).toBe(DEFAULT_TITLE);
|
||||
});
|
||||
|
||||
it('names a failed file and still sends the rest', async () => {
|
||||
const r = room(['b.ogg']);
|
||||
const res = await sendShareSet(r.port, 't', clips);
|
||||
expect(res.failed).toEqual(['b.ogg']);
|
||||
expect(res.sent).toBe(2);
|
||||
expect(r.album().files.map((f) => f.name)).toEqual(['a.ogg', 'c.txt']);
|
||||
// the next file falls back to the last event that exists, not to the failed one
|
||||
expect(r.events[2].content?.['m.relates_to']).toEqual(threadRelation('$e1', '$e2'));
|
||||
});
|
||||
|
||||
it('throws when the root cannot be sent, uploading nothing', async () => {
|
||||
let uploads = 0;
|
||||
const port: SharePort<ShareFile> = {
|
||||
send: async () => {
|
||||
throw new Error('M_FORBIDDEN');
|
||||
},
|
||||
contentOf: async () => {
|
||||
uploads += 1;
|
||||
return {};
|
||||
},
|
||||
};
|
||||
await expect(sendShareSet(port, 't', clips)).rejects.toThrow('M_FORBIDDEN');
|
||||
expect(uploads).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('after a send', () => {
|
||||
it('keeps the failed one of two same-named files, not both', async () => {
|
||||
const twins: ShareFile[] = [
|
||||
{ name: 'a.ogg', mimeType: 'audio/ogg' },
|
||||
{ name: 'a.ogg', mimeType: 'audio/ogg' },
|
||||
];
|
||||
let n = 0;
|
||||
const r = room();
|
||||
const port: SharePort<ShareFile> = {
|
||||
...r.port,
|
||||
contentOf: async (f) => {
|
||||
n += 1;
|
||||
if (n === 2) throw new Error('second upload failed');
|
||||
return r.port.contentOf(f);
|
||||
},
|
||||
};
|
||||
const res = await sendShareSet(port, 't', twins);
|
||||
expect(res.failedAt).toEqual([1]);
|
||||
expect(remainingAfter(twins, res)).toEqual([twins[1]]);
|
||||
});
|
||||
|
||||
it('keeps only the failed files picked, so a retry is one tap', async () => {
|
||||
const r = room(['b.ogg']);
|
||||
const res = await sendShareSet(r.port, 't', clips);
|
||||
expect(remainingAfter(clips, res).map((f) => f.name)).toEqual(['b.ogg']);
|
||||
expect(resultNote(res)).toBe('Shared 2. Not sent: b.ogg');
|
||||
});
|
||||
|
||||
it('keeps everything and says nothing was shared when every upload failed', async () => {
|
||||
const r = room(clips.map((c) => c.name));
|
||||
const res = await sendShareSet(r.port, 't', clips);
|
||||
expect(remainingAfter(clips, res)).toEqual(clips);
|
||||
expect(resultNote(res)).toBe('Nothing was shared. Not sent: a.ogg, b.ogg, c.txt');
|
||||
});
|
||||
|
||||
it('clears the pick on full success', async () => {
|
||||
const r = room();
|
||||
const res = await sendShareSet(r.port, 't', clips);
|
||||
expect(remainingAfter(clips, res)).toEqual([]);
|
||||
expect(resultNote(res)).toBe('Shared 3 files.');
|
||||
});
|
||||
});
|
||||
|
||||
describe('adding to an existing album', () => {
|
||||
it('sends no root; each file threads under the album, the first after `lastId`', async () => {
|
||||
const r = room();
|
||||
const sent: Record<string, unknown>[] = [];
|
||||
const port = {
|
||||
...r.port,
|
||||
send: async (c: Record<string, unknown>) => {
|
||||
sent.push(c);
|
||||
return `$n${sent.length}`;
|
||||
},
|
||||
};
|
||||
const res = await sendShareSet(
|
||||
port,
|
||||
{ albumId: '$root', lastId: '$last', lastTs: 1 },
|
||||
clips.slice(0, 2)
|
||||
);
|
||||
expect(res.albumId).toBe('$root');
|
||||
expect(res.sent).toBe(2);
|
||||
expect(sent.map((c) => c.msgtype)).toEqual(['m.audio', 'm.audio']);
|
||||
expect(sent.map((c) => c['m.relates_to'])).toEqual([
|
||||
threadRelation('$root', '$last'),
|
||||
threadRelation('$root', '$n1'),
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('refusals', () => {
|
||||
const refuse = (errcode: string): SharePort<ShareFile> => ({
|
||||
send: async () => '$e',
|
||||
contentOf: async () => {
|
||||
throw Object.assign(new Error('raw server text'), { errcode });
|
||||
},
|
||||
});
|
||||
|
||||
it('names the three upload refusals and nothing else', () => {
|
||||
expect(refusalOf({ errcode: 'M_TOO_LARGE' })).toBe('too large for this server');
|
||||
expect(refusalOf({ errcode: 'M_FORBIDDEN' })).toBe('not allowed to upload here');
|
||||
expect(refusalOf({ errcode: 'M_LIMIT_EXCEEDED' })).toBe(
|
||||
'uploading too fast, try again shortly'
|
||||
);
|
||||
expect(refusalOf({ errcode: 'M_UNKNOWN' })).toBeUndefined();
|
||||
expect(refusalOf({ errcode: 'constructor' })).toBeUndefined();
|
||||
expect(refusalOf(new Error('x'))).toBeUndefined();
|
||||
expect(refusalOf(null)).toBeUndefined();
|
||||
});
|
||||
|
||||
it('the note carries the reason beside each refused file', async () => {
|
||||
const res = await sendShareSet(refuse('M_TOO_LARGE'), 't', clips.slice(0, 2));
|
||||
expect(resultNote(res)).toBe(
|
||||
'Nothing was shared. Not sent: a.ogg (too large for this server), b.ogg (too large for this server)'
|
||||
);
|
||||
});
|
||||
|
||||
it('a failure the client saw, not the server, is named too', async () => {
|
||||
const dropped: SharePort<ShareFile> = {
|
||||
send: async () => '$e',
|
||||
contentOf: async () => {
|
||||
throw Object.assign(new Error('x'), {
|
||||
errcode: 'AbortError',
|
||||
info: { aborted: true, progressed: true },
|
||||
});
|
||||
},
|
||||
};
|
||||
const res = await sendShareSet(dropped, 't', clips.slice(0, 1));
|
||||
expect(resultNote(res)).toBe(
|
||||
'Nothing was shared. Not sent: a.ogg (the connection dropped partway through)'
|
||||
);
|
||||
});
|
||||
|
||||
it('an unnamed failure lists the bare name', async () => {
|
||||
const res = await sendShareSet(refuse('M_UNKNOWN'), 't', clips.slice(0, 1));
|
||||
expect(resultNote(res)).toBe('Nothing was shared. Not sent: a.ogg');
|
||||
});
|
||||
});
|
||||
|
||||
describe('stopping a send', () => {
|
||||
/** A port whose upload of `stopAt` aborts the signal as it runs, as the Stop button does mid-upload. */
|
||||
const stopping = (stopAt: string, abortAfterUpload = false) => {
|
||||
const ac = new AbortController();
|
||||
const r = room();
|
||||
const port: SharePort<ShareFile> = {
|
||||
...r.port,
|
||||
signal: ac.signal,
|
||||
contentOf: async (f) => {
|
||||
if (f.name !== stopAt) return r.port.contentOf(f);
|
||||
ac.abort();
|
||||
if (abortAfterUpload) return r.port.contentOf(f);
|
||||
throw Object.assign(new Error('aborted'), { name: 'AbortError' });
|
||||
},
|
||||
};
|
||||
return { port, r };
|
||||
};
|
||||
|
||||
it('an upload aborted mid-file leaves that file and the rest unsent, named as stopped', async () => {
|
||||
const { port, r } = stopping('b.ogg');
|
||||
const res = await sendShareSet(port, 't', clips);
|
||||
expect(res.sent).toBe(1);
|
||||
expect(res.failed).toEqual(['b.ogg', 'c.txt']);
|
||||
expect(res.failedAt).toEqual([1, 2]);
|
||||
expect(res.reasons).toEqual([CANCELLED, CANCELLED]);
|
||||
expect(r.album().files.map((f) => f.name)).toEqual(['a.ogg']);
|
||||
expect(remainingAfter(clips, res).map((f) => f.name)).toEqual(['b.ogg', 'c.txt']);
|
||||
expect(resultNote(res)).toBe('Shared 1. Not sent: b.ogg (stopped), c.txt (stopped)');
|
||||
});
|
||||
|
||||
it('a file whose upload finished after the stop is not sent', async () => {
|
||||
const { port, r } = stopping('b.ogg', true);
|
||||
const res = await sendShareSet(port, 't', clips);
|
||||
expect(res.sent).toBe(1);
|
||||
expect(res.failedAt).toEqual([1, 2]);
|
||||
expect(r.album().files.map((f) => f.name)).toEqual(['a.ogg']);
|
||||
});
|
||||
|
||||
it('a signal already aborted starts nothing and sends everything back as unsent', async () => {
|
||||
const r = room();
|
||||
const ac = new AbortController();
|
||||
ac.abort();
|
||||
let uploads = 0;
|
||||
const res = await sendShareSet(
|
||||
{
|
||||
...r.port,
|
||||
signal: ac.signal,
|
||||
contentOf: async (f) => {
|
||||
uploads += 1;
|
||||
return r.port.contentOf(f);
|
||||
},
|
||||
},
|
||||
{ albumId: '$a', lastId: '$l', lastTs: 1 },
|
||||
clips
|
||||
);
|
||||
expect(uploads).toBe(0);
|
||||
expect(res.sent).toBe(0);
|
||||
expect(res.failedAt).toEqual([0, 1, 2]);
|
||||
expect(r.events).toEqual([]);
|
||||
});
|
||||
|
||||
it('an abort that is not a stop is an ordinary failure', async () => {
|
||||
const r = room(['b.ogg']);
|
||||
const res = await sendShareSet({ ...r.port, signal: new AbortController().signal }, 't', clips);
|
||||
expect(res.failedAt).toEqual([1]);
|
||||
expect(res.reasons).toEqual([undefined]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('freshest', () => {
|
||||
const album = { albumId: '$alb', lastId: '$old', lastTs: 100 };
|
||||
it('moves lastId to a newer event of the same thread', () => {
|
||||
expect(
|
||||
freshest(album, [
|
||||
{ id: '$mid', ts: 150, threadRoot: '$alb' },
|
||||
{ id: '$new', ts: 200, threadRoot: '$alb' },
|
||||
])
|
||||
).toEqual({ albumId: '$alb', lastId: '$new', lastTs: 200 });
|
||||
});
|
||||
it('ignores older events and events of other threads or none', () => {
|
||||
expect(
|
||||
freshest(album, [
|
||||
{ id: '$older', ts: 50, threadRoot: '$alb' },
|
||||
{ id: '$other', ts: 900, threadRoot: '$else' },
|
||||
{ id: '$loose', ts: 900 },
|
||||
])
|
||||
).toEqual(album);
|
||||
});
|
||||
});
|
||||
|
||||
const file = (name: string, size?: number): Picked => ({ name, type: 'audio/ogg', size });
|
||||
const MB = 1024 * 1024;
|
||||
|
|
@ -1,6 +1,5 @@
|
|||
// Share a set of files at once: one album root (a text message) and one thread reply per file.
|
||||
// That is exactly the shape buildAlbums reads, so a set shared here and a set a Mind's mouth posts
|
||||
// are the same thing to every viewer. Ports are injected so the order and the failure rules are
|
||||
// Share a set of files at once: one album root (a text message) and one thread reply per file,
|
||||
// plus the share panel's state machine. Ports are injected so order and failure rules are
|
||||
// testable without a homeserver. See docs/file-zone.md, "Share a set".
|
||||
|
||||
import { uploadReason } from '../../utils/uploadReason';
|
||||
|
|
@ -136,3 +135,135 @@ export const resultNote = (result: ShareResult): string => {
|
|||
if (result.sent === 0) return `Nothing was shared. Not sent: ${failedList(result)}`;
|
||||
return `Shared ${result.sent}. Not sent: ${failedList(result)}`;
|
||||
};
|
||||
|
||||
export type Picked = { name: string; type: string; size?: number };
|
||||
|
||||
export type SharePhase =
|
||||
| { kind: 'idle' }
|
||||
| { kind: 'sending'; done: number }
|
||||
| { kind: 'done'; text: string };
|
||||
|
||||
export type ShareState<F extends Picked> = {
|
||||
files: F[];
|
||||
title: string;
|
||||
phase: SharePhase;
|
||||
/** Bumps whenever the pick is emptied, so the file input can be remounted and re-pick the same files. */
|
||||
epoch: number;
|
||||
};
|
||||
|
||||
export const ENCRYPTED_NOTE = 'Not shared: this room is encrypted.';
|
||||
|
||||
const MIB = 1024 * 1024;
|
||||
|
||||
/**
|
||||
* Files the homeserver would refuse for size (its `m.upload.size`, which Synapse enforces as a
|
||||
* limit, so a file of exactly that size goes), split from the rest before anything is sent. A
|
||||
* missing cap or size refuses nothing.
|
||||
*/
|
||||
export const splitBySize = <F extends Picked>(files: F[], cap: number | undefined) => {
|
||||
const over = (f: F) => cap !== undefined && f.size !== undefined && f.size > cap;
|
||||
return { sendable: files.filter((f) => !over(f)), tooLarge: files.filter(over) };
|
||||
};
|
||||
|
||||
const tooLargeNote = (names: string[], cap: number): string =>
|
||||
`Too large for this server (limit ${Math.round((cap / MIB) * 10) / 10} MB): ${names.join(', ')}`;
|
||||
|
||||
export type ShareDeps<F extends Picked> = {
|
||||
roomId: string;
|
||||
isEncrypted: () => boolean;
|
||||
/** Sends the files as one album; reports each settled file through onFile. */
|
||||
run: (files: F[], title: string, onFile: () => void, signal: AbortSignal) => Promise<ShareResult>;
|
||||
/** The homeserver's upload cap in bytes (`m.upload.size`), when it states one. */
|
||||
maxBytes?: () => number | undefined;
|
||||
/** Called after a send that reached the room, whatever it left unsent. */
|
||||
onSent?: () => void;
|
||||
};
|
||||
|
||||
/** Rooms with a share in flight. Module-level: leaving the page unmounts the panel, not the send. */
|
||||
const sending = new Set<string>();
|
||||
|
||||
export const createShareController = <F extends Picked>(deps: ShareDeps<F>) => {
|
||||
let state: ShareState<F> = { files: [], title: '', phase: { kind: 'idle' }, epoch: 0 };
|
||||
const listeners = new Set<() => void>();
|
||||
let running: AbortController | undefined;
|
||||
const set = (patch: Partial<ShareState<F>>) => {
|
||||
state = { ...state, ...patch };
|
||||
listeners.forEach((l) => l());
|
||||
};
|
||||
|
||||
const clear = () => set({ files: [], title: '', epoch: state.epoch + 1 });
|
||||
|
||||
const send = async () => {
|
||||
if (sending.has(deps.roomId) || state.files.length === 0) return;
|
||||
if (deps.isEncrypted()) {
|
||||
set({ phase: { kind: 'done', text: ENCRYPTED_NOTE } });
|
||||
return;
|
||||
}
|
||||
// Files over the cap are named and dropped from the pick before any upload or album root: a
|
||||
// retry cannot help them, and a root with nothing under it is a lone message nobody lists.
|
||||
const cap = deps.maxBytes?.();
|
||||
const { sendable, tooLarge } = splitBySize(state.files, cap);
|
||||
const sizeNote = tooLarge.length
|
||||
? tooLargeNote(
|
||||
tooLarge.map((f) => f.name),
|
||||
cap as number
|
||||
)
|
||||
: '';
|
||||
if (sendable.length === 0) {
|
||||
const phase: SharePhase = { kind: 'done', text: `Nothing was shared. ${sizeNote}` };
|
||||
set({ files: [], title: '', epoch: state.epoch + 1, phase });
|
||||
return;
|
||||
}
|
||||
sending.add(deps.roomId);
|
||||
const abort = new AbortController();
|
||||
running = abort;
|
||||
const { title } = state;
|
||||
const files = sendable;
|
||||
set({ files, phase: { kind: 'sending', done: 0 } });
|
||||
let settled = 0;
|
||||
try {
|
||||
const res = await deps.run(
|
||||
files,
|
||||
title,
|
||||
() => {
|
||||
settled += 1;
|
||||
set({ phase: { kind: 'sending', done: settled } });
|
||||
},
|
||||
abort.signal
|
||||
);
|
||||
deps.onSent?.();
|
||||
const left = remainingAfter(files, res);
|
||||
const phase: SharePhase = {
|
||||
kind: 'done',
|
||||
text: sizeNote ? `${resultNote(res)} ${sizeNote}` : resultNote(res),
|
||||
};
|
||||
// One notification: no state is ever drawn with the pick emptied and the send still running.
|
||||
if (left.length === 0) set({ files: [], title: '', epoch: state.epoch + 1, phase });
|
||||
else set({ files: left, phase });
|
||||
} catch (e: any) {
|
||||
const failure = `Could not share: ${e?.message ?? 'send failed'}`;
|
||||
set({ phase: { kind: 'done', text: sizeNote ? `${failure}. ${sizeNote}` : failure } });
|
||||
} finally {
|
||||
running = undefined;
|
||||
sending.delete(deps.roomId);
|
||||
}
|
||||
};
|
||||
|
||||
return {
|
||||
getState: () => state,
|
||||
subscribe: (l: () => void) => {
|
||||
listeners.add(l);
|
||||
return () => {
|
||||
listeners.delete(l);
|
||||
};
|
||||
},
|
||||
pick: (files: F[]) => set({ files, phase: { kind: 'idle' } }),
|
||||
setTitle: (title: string) => set({ title }),
|
||||
cancel: clear,
|
||||
/** Stops a send in flight: the running upload is aborted and the rest are left picked. */
|
||||
stop: () => running?.abort(),
|
||||
send,
|
||||
};
|
||||
};
|
||||
|
||||
export type ShareController<F extends Picked> = ReturnType<typeof createShareController<F>>;
|
||||
|
|
@ -1,5 +1,32 @@
|
|||
import { describe, expect, it } from 'vitest';
|
||||
import { Page, readPages } from './readPages';
|
||||
import { Page, mapLimit, readPages } from './useAlbums';
|
||||
|
||||
describe('mapLimit', () => {
|
||||
it('keeps result order and never exceeds the limit', async () => {
|
||||
let inFlight = 0;
|
||||
let peak = 0;
|
||||
const out = await mapLimit([5, 1, 4, 2, 3, 0], 2, async (n) => {
|
||||
inFlight += 1;
|
||||
peak = Math.max(peak, inFlight);
|
||||
await new Promise((r) => {
|
||||
setTimeout(r, n);
|
||||
});
|
||||
inFlight -= 1;
|
||||
return n * 10;
|
||||
});
|
||||
expect(out).toEqual([50, 10, 40, 20, 30, 0]);
|
||||
expect(peak).toBe(2);
|
||||
});
|
||||
it('handles an empty list and rejects when a call rejects', async () => {
|
||||
expect(await mapLimit([], 3, async (n) => n)).toEqual([]);
|
||||
await expect(
|
||||
mapLimit([1, 2], 2, async (n) => {
|
||||
if (n === 2) throw new Error('boom');
|
||||
return n;
|
||||
})
|
||||
).rejects.toThrow('boom');
|
||||
});
|
||||
});
|
||||
|
||||
const pager = (pages: Page<number>[]) => {
|
||||
const froms: (string | undefined)[] = [];
|
||||
|
|
@ -4,14 +4,59 @@ import { StateEvent } from '../../../types/matrix/room';
|
|||
import { useStateEvent } from '../../hooks/useStateEvent';
|
||||
import { useMatrixClient } from '../../hooks/useMatrixClient';
|
||||
import { useClientConfig } from '../../hooks/useClientConfig';
|
||||
import { Album, ZoneEvent, buildAlbums } from './buildAlbums';
|
||||
import { isFileZone } from './isFileZone';
|
||||
import { mapLimit } from './mapLimit';
|
||||
import { Page, readPages } from './readPages';
|
||||
import { Album, ZoneEvent, buildAlbums, isFileZone } from './buildAlbums';
|
||||
|
||||
const REPLY_FETCHES_IN_FLIGHT = 6;
|
||||
const REFRESH_MS = 30_000;
|
||||
|
||||
/** One page of a Matrix paginated endpoint: its events and the token for the next page, if any. */
|
||||
export type Page<T> = { chunk?: T[]; next_batch?: string };
|
||||
|
||||
/** Pages read per endpoint at most, so a runaway zone cannot hold the phone in a loop. */
|
||||
export const MAX_PAGES = 20;
|
||||
|
||||
/**
|
||||
* Reads every page of an endpoint by following `next_batch`, up to `maxPages`. `truncated` is true
|
||||
* when the cap stopped the read with more still to come, so a caller can say the list is partial.
|
||||
*/
|
||||
export const readPages = async <T>(
|
||||
fetchPage: (from: string | undefined) => Promise<Page<T>>,
|
||||
maxPages = MAX_PAGES
|
||||
): Promise<{ items: T[]; truncated: boolean }> => {
|
||||
const items: T[] = [];
|
||||
let from: string | undefined;
|
||||
for (let n = 0; n < maxPages; n += 1) {
|
||||
// eslint-disable-next-line no-await-in-loop
|
||||
const page = await fetchPage(from);
|
||||
items.push(...(page.chunk ?? []));
|
||||
// An empty page ends the read even if a token is returned: a server that keeps handing out
|
||||
// tokens with nothing behind them would otherwise spend every page of the cap.
|
||||
if (!page.next_batch || !page.chunk?.length) return { items, truncated: false };
|
||||
from = page.next_batch;
|
||||
}
|
||||
return { items, truncated: true };
|
||||
};
|
||||
|
||||
/** Like Promise.all(items.map(fn)) but with at most `limit` calls in flight; result order kept. */
|
||||
export const mapLimit = async <T, R>(
|
||||
items: T[],
|
||||
limit: number,
|
||||
fn: (item: T) => Promise<R>
|
||||
): Promise<R[]> => {
|
||||
const out = new Array<R>(items.length);
|
||||
let next = 0;
|
||||
const worker = async () => {
|
||||
while (next < items.length) {
|
||||
const i = next;
|
||||
next += 1;
|
||||
// eslint-disable-next-line no-await-in-loop
|
||||
out[i] = await fn(items[i]);
|
||||
}
|
||||
};
|
||||
await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));
|
||||
return out;
|
||||
};
|
||||
|
||||
/** True when the room is the file zone: by its create type, or listed in the client config. */
|
||||
export const useIsFileZone = (room: Room): boolean => {
|
||||
const config = useClientConfig();
|
||||
|
|
|
|||
|
|
@ -1,16 +0,0 @@
|
|||
import { describe, expect, it } from 'vitest';
|
||||
import { zoneView } from './zoneView';
|
||||
|
||||
describe('zoneView', () => {
|
||||
it('opens albums by default and the timeline for an event deep link', () => {
|
||||
expect(zoneView(undefined, undefined)).toBe('albums');
|
||||
expect(zoneView(undefined, '$e')).toBe('timeline');
|
||||
});
|
||||
it('lets an event link win over an earlier choice of albums', () => {
|
||||
expect(zoneView('albums', '$e')).toBe('timeline');
|
||||
});
|
||||
it('honours the choice when there is no event link', () => {
|
||||
expect(zoneView('albums', undefined)).toBe('albums');
|
||||
expect(zoneView('timeline', undefined)).toBe('timeline');
|
||||
});
|
||||
});
|
||||
|
|
@ -1,5 +0,0 @@
|
|||
export type ZoneView = 'albums' | 'timeline';
|
||||
|
||||
/** The view a file-zone room shows. A link to an event always wins; else the user's choice; else albums. */
|
||||
export const zoneView = (choice: ZoneView | undefined, eventId: string | undefined): ZoneView =>
|
||||
eventId ? 'timeline' : choice ?? 'albums';
|
||||
|
|
@ -5,7 +5,6 @@ import { StatusDivider } from './components';
|
|||
import { CallEmbed, useCallControlState } from '../../plugins/call';
|
||||
import { AsyncStatus, useAsyncCallback } from '../../hooks/useAsyncCallback';
|
||||
import { callEmbedAtom } from '../../state/callEmbed';
|
||||
import { PhoneHitSpread26 } from '../../styles/PhoneHit.css';
|
||||
|
||||
type MicrophoneButtonProps = {
|
||||
enabled: boolean;
|
||||
|
|
@ -27,7 +26,6 @@ function MicrophoneButton({ enabled, onToggle, disabled }: MicrophoneButtonProps
|
|||
>
|
||||
{(anchorRef) => (
|
||||
<IconButton
|
||||
className={PhoneHitSpread26}
|
||||
ref={anchorRef}
|
||||
variant={enabled ? 'Surface' : 'Warning'}
|
||||
fill="Soft"
|
||||
|
|
@ -61,7 +59,6 @@ function SoundButton({ enabled, onToggle, disabled }: SoundButtonProps) {
|
|||
>
|
||||
{(anchorRef) => (
|
||||
<IconButton
|
||||
className={PhoneHitSpread26}
|
||||
ref={anchorRef}
|
||||
variant={enabled ? 'Surface' : 'Warning'}
|
||||
fill="Soft"
|
||||
|
|
@ -102,7 +99,6 @@ function VideoButton({ enabled, onToggle, disabled }: VideoButtonProps) {
|
|||
>
|
||||
{(anchorRef) => (
|
||||
<IconButton
|
||||
className={PhoneHitSpread26}
|
||||
ref={anchorRef}
|
||||
variant={enabled ? 'Success' : 'Surface'}
|
||||
fill="Soft"
|
||||
|
|
@ -140,7 +136,6 @@ function ScreenShareButton({ enabled, onToggle, disabled }: ScreenShareButtonPro
|
|||
>
|
||||
{(anchorRef) => (
|
||||
<IconButton
|
||||
className={PhoneHitSpread26}
|
||||
ref={anchorRef}
|
||||
variant={enabled ? 'Success' : 'Surface'}
|
||||
fill="Soft"
|
||||
|
|
|
|||
|
|
@ -25,7 +25,6 @@ import {
|
|||
SoundButton,
|
||||
VideoButton,
|
||||
} from './Controls';
|
||||
import { PhoneHitSpread40 } from '../../styles/PhoneHit.css';
|
||||
import { CallEmbed, useCallControlState } from '../../plugins/call';
|
||||
import { useResizeObserver } from '../../hooks/useResizeObserver';
|
||||
import { stopPropagation } from '../../utils/keyboard';
|
||||
|
|
@ -170,7 +169,6 @@ export function CallControls({ callEmbed }: CallControlsProps) {
|
|||
}
|
||||
>
|
||||
<IconButton
|
||||
className={PhoneHitSpread40}
|
||||
variant="Surface"
|
||||
fill="Soft"
|
||||
radii="400"
|
||||
|
|
|
|||
|
|
@ -4,7 +4,6 @@ import { useAtom } from 'jotai';
|
|||
import * as css from './styles.css';
|
||||
import { callChatAtom } from '../../state/callEmbed';
|
||||
import { AsyncStatus, useAsyncCallback } from '../../hooks/useAsyncCallback';
|
||||
import { PhoneHitSpread40 } from '../../styles/PhoneHit.css';
|
||||
|
||||
export function ControlDivider() {
|
||||
return (
|
||||
|
|
@ -32,7 +31,6 @@ export function MicrophoneButton({ enabled, onToggle }: MicrophoneButtonProps) {
|
|||
>
|
||||
{(anchorRef) => (
|
||||
<IconButton
|
||||
className={PhoneHitSpread40}
|
||||
ref={anchorRef}
|
||||
variant={enabled ? 'Surface' : 'Warning'}
|
||||
fill="Soft"
|
||||
|
|
@ -66,7 +64,6 @@ export function SoundButton({ enabled, onToggle }: SoundButtonProps) {
|
|||
>
|
||||
{(anchorRef) => (
|
||||
<IconButton
|
||||
className={PhoneHitSpread40}
|
||||
ref={anchorRef}
|
||||
variant={enabled ? 'Surface' : 'Warning'}
|
||||
fill="Soft"
|
||||
|
|
@ -106,7 +103,6 @@ export function VideoButton({ enabled, onToggle }: VideoButtonProps) {
|
|||
>
|
||||
{(anchorRef) => (
|
||||
<IconButton
|
||||
className={PhoneHitSpread40}
|
||||
ref={anchorRef}
|
||||
variant={enabled ? 'Success' : 'Surface'}
|
||||
fill="Soft"
|
||||
|
|
@ -144,7 +140,6 @@ export function ScreenShareButton({ enabled, onToggle }: ScreenShareButtonProps)
|
|||
>
|
||||
{(anchorRef) => (
|
||||
<IconButton
|
||||
className={PhoneHitSpread40}
|
||||
ref={anchorRef}
|
||||
variant={enabled ? 'Success' : 'Surface'}
|
||||
fill="Soft"
|
||||
|
|
@ -175,7 +170,6 @@ export function ChatButton() {
|
|||
>
|
||||
{(anchorRef) => (
|
||||
<IconButton
|
||||
className={PhoneHitSpread40}
|
||||
ref={anchorRef}
|
||||
variant={chat ? 'Success' : 'Surface'}
|
||||
fill="Soft"
|
||||
|
|
|
|||
|
|
@ -30,7 +30,6 @@ import {
|
|||
AccountDataSubmitCallback,
|
||||
} from '../../../components/AccountDataEditor';
|
||||
import { useMatrixClient } from '../../../hooks/useMatrixClient';
|
||||
import { PhoneHit } from '../../../styles/PhoneHit.css';
|
||||
|
||||
type DeveloperToolsProps = {
|
||||
requestClose: () => void;
|
||||
|
|
@ -93,7 +92,7 @@ export function DeveloperTools({ requestClose }: DeveloperToolsProps) {
|
|||
</Text>
|
||||
</Box>
|
||||
<Box shrink="No">
|
||||
<IconButton className={PhoneHit} onClick={requestClose} variant="Surface">
|
||||
<IconButton onClick={requestClose} variant="Surface">
|
||||
<Icon src={Icons.Cross} />
|
||||
</IconButton>
|
||||
</Box>
|
||||
|
|
|
|||
|
|
@ -22,7 +22,6 @@ import { useTextAreaCodeEditor } from '../../../hooks/useTextAreaCodeEditor';
|
|||
import { AsyncStatus, useAsyncCallback } from '../../../hooks/useAsyncCallback';
|
||||
import { syntaxErrorPosition } from '../../../utils/dom';
|
||||
import { Cursor } from '../../../plugins/text-area';
|
||||
import { PhoneHit } from '../../../styles/PhoneHit.css';
|
||||
|
||||
const EDITOR_INTENT_SPACE_COUNT = 2;
|
||||
|
||||
|
|
@ -119,7 +118,7 @@ export function SendRoomEvent({ type, stateKey, requestClose }: SendRoomEventPro
|
|||
</Chip>
|
||||
</Box>
|
||||
<Box shrink="No">
|
||||
<IconButton className={PhoneHit} onClick={requestClose} variant="Surface">
|
||||
<IconButton onClick={requestClose} variant="Surface">
|
||||
<Icon src={Icons.Cross} />
|
||||
</IconButton>
|
||||
</Box>
|
||||
|
|
|
|||
|
|
@ -31,7 +31,6 @@ import { usePowerLevels } from '../../../hooks/usePowerLevels';
|
|||
import { useTextAreaCodeEditor } from '../../../hooks/useTextAreaCodeEditor';
|
||||
import { useRoomCreators } from '../../../hooks/useRoomCreators';
|
||||
import { useRoomPermissions } from '../../../hooks/useRoomPermissions';
|
||||
import { PhoneHit } from '../../../styles/PhoneHit.css';
|
||||
|
||||
const EDITOR_INTENT_SPACE_COUNT = 2;
|
||||
|
||||
|
|
@ -276,7 +275,7 @@ export function StateEventEditor({ type, stateKey, requestClose }: StateEventEdi
|
|||
</Chip>
|
||||
</Box>
|
||||
<Box shrink="No">
|
||||
<IconButton className={PhoneHit} onClick={requestClose} variant="Surface">
|
||||
<IconButton onClick={requestClose} variant="Surface">
|
||||
<Icon src={Icons.Cross} />
|
||||
</IconButton>
|
||||
</Box>
|
||||
|
|
|
|||
|
|
@ -4,7 +4,6 @@ import { Page, PageContent, PageHeader } from '../../../components/page';
|
|||
import { ImagePack } from '../../../plugins/custom-emoji';
|
||||
import { ImagePackView } from '../../../components/image-pack-view';
|
||||
import { RoomPacks } from './RoomPacks';
|
||||
import { PhoneHit } from '../../../styles/PhoneHit.css';
|
||||
|
||||
type EmojisStickersProps = {
|
||||
requestClose: () => void;
|
||||
|
|
@ -30,7 +29,7 @@ export function EmojisStickers({ requestClose }: EmojisStickersProps) {
|
|||
</Text>
|
||||
</Box>
|
||||
<Box shrink="No">
|
||||
<IconButton className={PhoneHit} onClick={requestClose} variant="Surface">
|
||||
<IconButton onClick={requestClose} variant="Surface">
|
||||
<Icon src={Icons.Cross} />
|
||||
</IconButton>
|
||||
</Box>
|
||||
|
|
|
|||
|
|
@ -40,7 +40,6 @@ import { AsyncStatus, useAsyncCallback } from '../../../hooks/useAsyncCallback';
|
|||
import { useAlive } from '../../../hooks/useAlive';
|
||||
import { useRoomCreators } from '../../../hooks/useRoomCreators';
|
||||
import { useRoomPermissions } from '../../../hooks/useRoomPermissions';
|
||||
import { PhoneHit } from '../../../styles/PhoneHit.css';
|
||||
|
||||
type CreatePackTileProps = {
|
||||
packs: ImagePack[];
|
||||
|
|
@ -216,7 +215,6 @@ export function RoomPacks({ onViewPack }: RoomPacksProps) {
|
|||
{canEdit &&
|
||||
(removed ? (
|
||||
<IconButton
|
||||
className={PhoneHit}
|
||||
size="300"
|
||||
radii="Pill"
|
||||
variant="Critical"
|
||||
|
|
@ -227,7 +225,6 @@ export function RoomPacks({ onViewPack }: RoomPacksProps) {
|
|||
</IconButton>
|
||||
) : (
|
||||
<IconButton
|
||||
className={PhoneHit}
|
||||
size="300"
|
||||
radii="Pill"
|
||||
variant="Secondary"
|
||||
|
|
|
|||
|
|
@ -28,7 +28,6 @@ import { useRoom } from '../../../hooks/useRoom';
|
|||
import { useStateEvent } from '../../../hooks/useStateEvent';
|
||||
import { stopPropagation } from '../../../utils/keyboard';
|
||||
import { RoomPermissionsAPI } from '../../../hooks/useRoomPermissions';
|
||||
import { PhoneHit } from '../../../styles/PhoneHit.css';
|
||||
|
||||
const ROOM_ENC_ALGO = 'm.megolm.v1.aes-sha2';
|
||||
|
||||
|
|
@ -125,7 +124,6 @@ export function RoomEncryption({ permissions }: RoomEncryptionProps) {
|
|||
<Text size="H4">Enable Encryption</Text>
|
||||
</Box>
|
||||
<IconButton
|
||||
className={PhoneHit}
|
||||
size="300"
|
||||
onClick={() => setPrompt(false)}
|
||||
radii="300"
|
||||
|
|
|
|||
|
|
@ -39,7 +39,6 @@ import { useAlive } from '../../../hooks/useAlive';
|
|||
import { creatorsSupported } from '../../../utils/matrix';
|
||||
import { useRoomCreators } from '../../../hooks/useRoomCreators';
|
||||
import { BreakWord } from '../../../styles/Text.css';
|
||||
import { PhoneHit } from '../../../styles/PhoneHit.css';
|
||||
|
||||
function RoomUpgradeDialog({ requestClose }: { requestClose: () => void }) {
|
||||
const mx = useMatrixClient();
|
||||
|
|
@ -106,7 +105,7 @@ function RoomUpgradeDialog({ requestClose }: { requestClose: () => void }) {
|
|||
<Box grow="Yes">
|
||||
<Text size="H4">{room.isSpaceRoom() ? 'Space Upgrade' : 'Room Upgrade'}</Text>
|
||||
</Box>
|
||||
<IconButton className={PhoneHit} size="300" onClick={requestClose} radii="300">
|
||||
<IconButton size="300" onClick={requestClose} radii="300">
|
||||
<Icon src={Icons.Cross} />
|
||||
</IconButton>
|
||||
</Header>
|
||||
|
|
|
|||
|
|
@ -56,7 +56,6 @@ import { useSpaceOptionally } from '../../../hooks/useSpace';
|
|||
import { useFlattenPowerTagMembers, useGetMemberPowerTag } from '../../../hooks/useMemberPowerTag';
|
||||
import { useRoomCreators } from '../../../hooks/useRoomCreators';
|
||||
import { getMouseEventCords } from '../../../utils/dom';
|
||||
import { PhoneHit } from '../../../styles/PhoneHit.css';
|
||||
|
||||
const SEARCH_OPTIONS: UseAsyncSearchOptions = {
|
||||
limit: 1000,
|
||||
|
|
@ -162,7 +161,7 @@ export function Members({ requestClose }: MembersProps) {
|
|||
</Text>
|
||||
</Box>
|
||||
<Box shrink="No">
|
||||
<IconButton className={PhoneHit} onClick={requestClose} variant="Surface">
|
||||
<IconButton onClick={requestClose} variant="Surface">
|
||||
<Icon src={Icons.Cross} />
|
||||
</IconButton>
|
||||
</Box>
|
||||
|
|
@ -278,7 +277,6 @@ export function Members({ requestClose }: MembersProps) {
|
|||
anchorRef={scrollTopAnchorRef}
|
||||
>
|
||||
<IconButton
|
||||
className={PhoneHit}
|
||||
onClick={() => virtualizer.scrollToOffset(0)}
|
||||
variant="Surface"
|
||||
radii="Pill"
|
||||
|
|
|
|||
|
|
@ -49,7 +49,6 @@ import { useAlive } from '../../../hooks/useAlive';
|
|||
import { BetaNoticeBadge } from '../../../components/BetaNoticeBadge';
|
||||
import { getPowerTagIconSrc } from '../../../hooks/useMemberPowerTag';
|
||||
import { creatorsSupported } from '../../../utils/matrix';
|
||||
import { PhoneHit } from '../../../styles/PhoneHit.css';
|
||||
|
||||
type EditPowerProps = {
|
||||
maxPower: number;
|
||||
|
|
@ -370,7 +369,7 @@ export function PowersEditor({ powerLevels, requestClose }: PowersEditorProps) {
|
|||
</Chip>
|
||||
</Box>
|
||||
<Box shrink="No">
|
||||
<IconButton className={PhoneHit} onClick={requestClose} variant="Surface">
|
||||
<IconButton onClick={requestClose} variant="Surface">
|
||||
<Icon src={Icons.Cross} />
|
||||
</IconButton>
|
||||
</Box>
|
||||
|
|
|
|||
|
|
@ -24,7 +24,6 @@ import {
|
|||
import { CreateRoomModalState } from '../../state/createRoomModal';
|
||||
import { stopPropagation } from '../../utils/keyboard';
|
||||
import { CreateRoomType } from '../../components/create-room/types';
|
||||
import { PhoneHit } from '../../styles/PhoneHit.css';
|
||||
|
||||
type CreateRoomModalProps = {
|
||||
state: CreateRoomModalState;
|
||||
|
|
@ -64,7 +63,7 @@ function CreateRoomModal({ state }: CreateRoomModalProps) {
|
|||
</Text>
|
||||
</Box>
|
||||
<Box shrink="No">
|
||||
<IconButton className={PhoneHit} size="300" radii="300" onClick={closeDialog}>
|
||||
<IconButton size="300" radii="300" onClick={closeDialog}>
|
||||
<Icon src={Icons.Cross} />
|
||||
</IconButton>
|
||||
</Box>
|
||||
|
|
|
|||
|
|
@ -23,7 +23,6 @@ import {
|
|||
} from '../../state/hooks/createSpaceModal';
|
||||
import { CreateSpaceModalState } from '../../state/createSpaceModal';
|
||||
import { stopPropagation } from '../../utils/keyboard';
|
||||
import { PhoneHit } from '../../styles/PhoneHit.css';
|
||||
|
||||
type CreateSpaceModalProps = {
|
||||
state: CreateSpaceModalState;
|
||||
|
|
@ -62,7 +61,7 @@ function CreateSpaceModal({ state }: CreateSpaceModalProps) {
|
|||
<Text size="H4">New Space</Text>
|
||||
</Box>
|
||||
<Box shrink="No">
|
||||
<IconButton className={PhoneHit} size="300" radii="300" onClick={closeDialog}>
|
||||
<IconButton size="300" radii="300" onClick={closeDialog}>
|
||||
<Icon src={Icons.Cross} />
|
||||
</IconButton>
|
||||
</Box>
|
||||
|
|
|
|||
|
|
@ -1,7 +1,6 @@
|
|||
import React, { useMemo } from 'react';
|
||||
import { useNavigate, useParams } from 'react-router-dom';
|
||||
import { Box, Icon, IconButton, Icons, Scroll, Text } from 'folds';
|
||||
import { PhoneHit } from '../../styles/PhoneHit.css';
|
||||
import { Page, PageContent, PageContentCenter, PageHeader } from '../../components/page';
|
||||
import { ScreenSize, useScreenSizeContext } from '../../hooks/useScreenSize';
|
||||
import { getHomePath } from '../../pages/pathUtils';
|
||||
|
|
@ -28,7 +27,6 @@ export function Desk() {
|
|||
<Box grow="Yes" basis="No">
|
||||
{phone && (
|
||||
<IconButton
|
||||
className={PhoneHit}
|
||||
aria-label="Back to rooms"
|
||||
onClick={() => navigate(getHomePath())}
|
||||
>
|
||||
|
|
|
|||
|
|
@ -37,10 +37,11 @@ export const openCount = (
|
|||
unverified: ReadonlySet<string> | undefined
|
||||
): number => (unverified ? buildDesk(list, unverified).counts.open : 0);
|
||||
|
||||
/** A Mind's desk, pinned at the top of its navigator group: always there, with the open count when there is one. */
|
||||
/** A Mind's desk, pinned at the top of its navigator group when a desk source exists. */
|
||||
export function DeskEntry({ mind }: { mind: string }) {
|
||||
const list = useMemo(() => deskFor(mind), [mind]);
|
||||
const unverified = useUnverified(list);
|
||||
if (!list) return null;
|
||||
// The same count the desk page shows; until the hash check lands there is no count to show.
|
||||
return <DeskLink mind={mind} open={openCount(list, unverified)} />;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -291,12 +291,12 @@ describe('DeskEntry', () => {
|
|||
expect(bare(link(0))).toBe('Desk');
|
||||
expect(link(0)).toContain('href="/desk/void"');
|
||||
});
|
||||
it('is pinned when nothing is published, and when only settled forks exist', () => {
|
||||
[undefined, { ...STATES.settled, open_count: 0 }].forEach((state) => {
|
||||
setDeskSource(() => state);
|
||||
expect(bare(entry('void'))).toBe('Desk');
|
||||
expect(entry('void')).toContain('href="/desk/void"');
|
||||
});
|
||||
it('is omitted when nothing is published, and pinned when settled forks exist', () => {
|
||||
setDeskSource(() => undefined);
|
||||
expect(entry('void')).toBe('');
|
||||
setDeskSource(() => ({ ...STATES.settled, open_count: 0 }));
|
||||
expect(bare(entry('void'))).toBe('Desk');
|
||||
expect(entry('void')).toContain('href="/desk/void"');
|
||||
});
|
||||
it('shows no count before the hash check has landed, so a card about to be withdrawn is never counted', () => {
|
||||
setDeskSource(() => STATES.blocked);
|
||||
|
|
|
|||
|
|
@ -151,7 +151,7 @@ export function DeskView({ mind, label, list, unverified, now = Date.now() }: De
|
|||
const desk = buildDesk(list, unverified);
|
||||
const skyInk = useSkyInk();
|
||||
// Slice 1 has no session, so nothing on the desk is the viewer's answer yet.
|
||||
const mood = deskMood(desk.counts.open, 0);
|
||||
const mood = deskMood(desk.counts.open);
|
||||
return (
|
||||
<section aria-label={`${label}'s desk`}>
|
||||
<Status desk={desk} label={label} />
|
||||
|
|
|
|||
|
|
@ -4,53 +4,19 @@ import { MOOD_POSE, deskMood } from './deskMood';
|
|||
|
||||
describe('deskMood', () => {
|
||||
it('is neutral with the desk clear when nothing is open', () => {
|
||||
expect(deskMood(0, 0)).toEqual({
|
||||
expect(deskMood(0)).toEqual({
|
||||
mood: 'neutral',
|
||||
pose: 'neutral',
|
||||
line: "Desk's clear. I'll wave when something lands.",
|
||||
});
|
||||
});
|
||||
it('is triumph when every open fork is answered', () => {
|
||||
expect(deskMood(3, 3).mood).toBe('triumph');
|
||||
expect(deskMood(1, 1).mood).toBe('triumph');
|
||||
});
|
||||
it('is thinking when none is answered, and says whether it is one fork or several', () => {
|
||||
expect(deskMood(1, 0)).toMatchObject({ mood: 'thinking', line: 'Just one fork on the desk.' });
|
||||
expect(deskMood(4, 0)).toMatchObject({
|
||||
it('is thinking when forks are open, and says whether it is one fork or several', () => {
|
||||
expect(deskMood(1)).toMatchObject({ mood: 'thinking', line: 'Just one fork on the desk.' });
|
||||
expect(deskMood(4)).toMatchObject({
|
||||
mood: 'thinking',
|
||||
line: '4 forks on the desk. No rush.',
|
||||
});
|
||||
});
|
||||
it('is determined partway, counting what is left', () => {
|
||||
expect(deskMood(5, 2)).toMatchObject({ mood: 'determined', line: '3 to go.' });
|
||||
});
|
||||
it('is happy when the pick is the recommendation', () => {
|
||||
expect(deskMood(2, 0, { type: 'picked', choice: 'B', recommended: 'B' }).mood).toBe('happy');
|
||||
});
|
||||
it('is surprised, and asks for a line on why, when the pick differs', () => {
|
||||
expect(deskMood(2, 0, { type: 'picked', choice: 'A', recommended: 'B' })).toMatchObject({
|
||||
mood: 'surprised',
|
||||
line: expect.stringContaining('A line in the note on why helps'),
|
||||
});
|
||||
});
|
||||
it('is surprised, not happy, when there is no recommendation to match', () => {
|
||||
expect(deskMood(2, 0, { type: 'picked', choice: 'A' }).mood).toBe('surprised');
|
||||
});
|
||||
it('is note when a pick is cleared, saying the note can carry the answer', () => {
|
||||
expect(deskMood(2, 1, { type: 'cleared' })).toMatchObject({
|
||||
mood: 'note',
|
||||
line: expect.stringContaining('note can carry the answer on its own'),
|
||||
});
|
||||
});
|
||||
it('is concerned when a send failed, even with everything answered', () => {
|
||||
expect(deskMood(2, 2, { type: 'sendFailed' }).mood).toBe('concerned');
|
||||
});
|
||||
it('is surprised when a new fork arrives, even on a clear desk', () => {
|
||||
expect(deskMood(0, 0, { type: 'newFork' })).toMatchObject({
|
||||
mood: 'surprised',
|
||||
line: 'New fork on the desk!',
|
||||
});
|
||||
});
|
||||
it('maps every mood to a label every Mind in the catalogue can show', () => {
|
||||
Object.values(MOOD_POSE).forEach((pose) =>
|
||||
MINDS.forEach((mind) => expect(resolvePose(mind, pose)).toBe(pose))
|
||||
|
|
|
|||
|
|
@ -1,75 +1,27 @@
|
|||
/**
|
||||
* The booth Persona's reactions, from the original Fork Desk's mood() and choose() rules. A pure function of
|
||||
* what is on the desk and the last thing that happened; it is the desk's character, so each rule is tested.
|
||||
* The booth Persona's reactions while the desk is read-only. A pure function of what is open on
|
||||
* the desk.
|
||||
*/
|
||||
|
||||
/** The original's nine moods. */
|
||||
export type Mood =
|
||||
| 'idle'
|
||||
| 'neutral'
|
||||
| 'thinking'
|
||||
| 'happy'
|
||||
| 'surprised'
|
||||
| 'note'
|
||||
| 'determined'
|
||||
| 'triumph'
|
||||
| 'concerned';
|
||||
|
||||
/** What last happened; `none` means nothing since the page opened or the last event wore off. */
|
||||
export type DeskEvent =
|
||||
| { type: 'none' }
|
||||
| { type: 'picked'; choice: string; recommended?: string }
|
||||
| { type: 'cleared' }
|
||||
| { type: 'sendFailed' }
|
||||
| { type: 'newFork' };
|
||||
export type Mood = 'neutral' | 'thinking';
|
||||
|
||||
/**
|
||||
* Each mood on the shared cast-art labels (neutral, happy, amused, thinking, annoyed, surprised) that every
|
||||
* Mind has, so the booth never asks a Mind for art it lacks.
|
||||
* Each mood on the shared cast-art labels (neutral, thinking) that every Mind has, so the booth
|
||||
* never asks a Mind for art it lacks.
|
||||
*/
|
||||
export const MOOD_POSE: Record<Mood, string> = {
|
||||
idle: 'neutral',
|
||||
neutral: 'neutral',
|
||||
thinking: 'thinking',
|
||||
happy: 'happy',
|
||||
surprised: 'surprised',
|
||||
note: 'thinking',
|
||||
determined: 'thinking',
|
||||
triumph: 'happy',
|
||||
concerned: 'surprised',
|
||||
};
|
||||
|
||||
export type DeskMood = { mood: Mood; pose: string; line: string };
|
||||
|
||||
const say = (mood: Mood, line: string): DeskMood => ({ mood, pose: MOOD_POSE[mood], line });
|
||||
|
||||
export const deskMood = (
|
||||
open: number,
|
||||
answered: number,
|
||||
event: DeskEvent = { type: 'none' }
|
||||
): DeskMood => {
|
||||
switch (event.type) {
|
||||
case 'sendFailed':
|
||||
return say('concerned', "That one didn't save. Give it another try in a moment?");
|
||||
case 'newFork':
|
||||
return say('surprised', 'New fork on the desk!');
|
||||
case 'cleared':
|
||||
return say('note', 'Pick cleared. Your note can carry the answer on its own.');
|
||||
case 'picked':
|
||||
return event.recommended !== undefined && event.choice === event.recommended
|
||||
? say('happy', "That's the one I'd have picked too.")
|
||||
: say('surprised', 'Off-script. A line in the note on why helps the next brief.');
|
||||
default:
|
||||
break;
|
||||
}
|
||||
export const deskMood = (open: number): DeskMood => {
|
||||
if (open === 0) return say('neutral', "Desk's clear. I'll wave when something lands.");
|
||||
if (answered >= open)
|
||||
return say('triumph', 'All answered! I will carry these back and admit them.');
|
||||
if (answered === 0) {
|
||||
return say(
|
||||
'thinking',
|
||||
open === 1 ? 'Just one fork on the desk.' : `${open} forks on the desk. No rush.`
|
||||
);
|
||||
}
|
||||
return say('determined', `${open - answered} to go.`);
|
||||
return say(
|
||||
'thinking',
|
||||
open === 1 ? 'Just one fork on the desk.' : `${open} forks on the desk. No rush.`
|
||||
);
|
||||
};
|
||||
|
|
|
|||
|
|
@ -5,7 +5,7 @@ import { Avatar, Box, Icon, Icons, Text } from 'folds';
|
|||
import { NavGutter, NavItem, NavItemContent, NavLink } from '../../components/nav';
|
||||
import { NAV_ROOM_ICON_REST_OPACITY, NavLabel } from '../../components/nav/styles.css';
|
||||
import { EstateRoom } from './buildEstate';
|
||||
import { isFileZone } from '../albums/isFileZone';
|
||||
import { isFileZone } from '../albums/buildAlbums';
|
||||
import { useClientConfig } from '../../hooks/useClientConfig';
|
||||
import { MINDS } from '../../components/message/pose/poses';
|
||||
import { useMatrixClient } from '../../hooks/useMatrixClient';
|
||||
|
|
|
|||
|
|
@ -10,7 +10,6 @@ import { useMatrixClient } from '../../hooks/useMatrixClient';
|
|||
import { allRoomsAtom } from '../../state/room-list/roomList';
|
||||
import { ScreenSize, useScreenSizeContext } from '../../hooks/useScreenSize';
|
||||
import { BackRouteHandler } from '../../components/BackRouteHandler';
|
||||
import { PhoneHit } from '../../styles/PhoneHit.css';
|
||||
|
||||
type JoinBeforeNavigateProps = { roomIdOrAlias: string; eventId?: string; viaServers?: string[] };
|
||||
export function JoinBeforeNavigate({
|
||||
|
|
@ -39,7 +38,7 @@ export function JoinBeforeNavigate({
|
|||
{screenSize === ScreenSize.Mobile && (
|
||||
<BackRouteHandler>
|
||||
{(onBack) => (
|
||||
<IconButton className={PhoneHit} onClick={onBack}>
|
||||
<IconButton onClick={onBack}>
|
||||
<Icon src={Icons.ArrowLeft} />
|
||||
</IconButton>
|
||||
)}
|
||||
|
|
|
|||
|
|
@ -30,7 +30,6 @@ import { IPowerLevels } from '../../hooks/usePowerLevels';
|
|||
import { getRoomCreatorsForRoomId } from '../../hooks/useRoomCreators';
|
||||
import { getRoomPermissionsAPI } from '../../hooks/useRoomPermissions';
|
||||
import { InviteUserPrompt } from '../../components/invite-user-prompt';
|
||||
import { PhoneHitSpread24 } from '../../styles/PhoneHit.css';
|
||||
|
||||
type HierarchyItemWithParent = HierarchyItem & {
|
||||
parentId: string;
|
||||
|
|
@ -232,7 +231,6 @@ export function HierarchyItemMenu({
|
|||
return (
|
||||
<Box gap="200" alignItems="Center" shrink="No">
|
||||
<IconButton
|
||||
className={PhoneHitSpread24}
|
||||
onClick={handleOpenMenu}
|
||||
size="300"
|
||||
variant="SurfaceVariant"
|
||||
|
|
|
|||
|
|
@ -48,7 +48,6 @@ import { useGetRoom } from '../../hooks/useGetRoom';
|
|||
import { AsyncStatus, useAsyncCallback } from '../../hooks/useAsyncCallback';
|
||||
import { getRoomPermissionsAPI } from '../../hooks/useRoomPermissions';
|
||||
import { getRoomCreatorsForRoomId } from '../../hooks/useRoomCreators';
|
||||
import { PhoneHit } from '../../styles/PhoneHit.css';
|
||||
|
||||
const useCanDropLobbyItem = (
|
||||
space: Room,
|
||||
|
|
@ -414,7 +413,6 @@ export function Lobby() {
|
|||
onVisibilityChange={setOnTop}
|
||||
>
|
||||
<IconButton
|
||||
className={PhoneHit}
|
||||
onClick={() => virtualizer.scrollToOffset(0)}
|
||||
variant="SurfaceVariant"
|
||||
radii="Pill"
|
||||
|
|
|
|||
|
|
@ -38,7 +38,6 @@ import { useOpenSpaceSettings } from '../../state/hooks/spaceSettings';
|
|||
import { useRoomCreators } from '../../hooks/useRoomCreators';
|
||||
import { useRoomPermissions } from '../../hooks/useRoomPermissions';
|
||||
import { InviteUserPrompt } from '../../components/invite-user-prompt';
|
||||
import { PhoneHit } from '../../styles/PhoneHit.css';
|
||||
|
||||
type LobbyMenuProps = {
|
||||
powerLevels: IPowerLevels;
|
||||
|
|
@ -166,7 +165,7 @@ export function LobbyHeader({ showProfile, powerLevels }: LobbyHeaderProps) {
|
|||
<Box shrink="No">
|
||||
<BackRouteHandler>
|
||||
{(onBack) => (
|
||||
<IconButton className={PhoneHit} fill="None" onClick={onBack}>
|
||||
<IconButton fill="None" onClick={onBack}>
|
||||
<Icon src={Icons.ArrowLeft} />
|
||||
</IconButton>
|
||||
)}
|
||||
|
|
@ -241,7 +240,6 @@ export function LobbyHeader({ showProfile, powerLevels }: LobbyHeaderProps) {
|
|||
>
|
||||
{(triggerRef) => (
|
||||
<IconButton
|
||||
className={PhoneHit}
|
||||
fill="None"
|
||||
onClick={handleOpenMenu}
|
||||
ref={triggerRef}
|
||||
|
|
|
|||
|
|
@ -23,7 +23,6 @@ import { SearchResultGroup } from './SearchResultGroup';
|
|||
import { SearchInput } from './SearchInput';
|
||||
import { SearchFilters } from './SearchFilters';
|
||||
import { VirtualTile } from '../../components/virtualizer';
|
||||
import { PhoneHit } from '../../styles/PhoneHit.css';
|
||||
|
||||
const useSearchPathSearchParams = (searchParams: URLSearchParams): _SearchPathSearchParams =>
|
||||
useMemo(
|
||||
|
|
@ -194,7 +193,6 @@ export function MessageSearch({
|
|||
<Box direction="Column" gap="700">
|
||||
<ScrollTopContainer scrollRef={scrollRef} anchorRef={scrollTopAnchorRef}>
|
||||
<IconButton
|
||||
className={PhoneHit}
|
||||
onClick={() => virtualizer.scrollToOffset(0)}
|
||||
variant="SurfaceVariant"
|
||||
radii="Pill"
|
||||
|
|
|
|||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue