Merge Ratatoskr Cut R1 (dead code, 109 KiB LUT, shader stall, baker theater) with dev
All checks were successful
Rat dev preview / Build dev preview (push) Successful in 5m31s

This commit is contained in:
Meta Vens 2026-12-03 21:48:11 +01:00
commit 445e78fb36
157 changed files with 841 additions and 3502 deletions

View file

@ -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';
}
};

View file

@ -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' },
]);
});

View file

@ -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>

View file

@ -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"

View file

@ -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>

View file

@ -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>

View file

@ -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"

View file

@ -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"

View file

@ -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,
});

View file

@ -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)}

View file

@ -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}

View file

@ -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>

View file

@ -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>

View file

@ -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>

View file

@ -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"

View file

@ -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>

View file

@ -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>

View file

@ -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>

View file

@ -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>

View file

@ -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'} />

View file

@ -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();

View file

@ -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}
>

View file

@ -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\}>/);
});
});

View file

@ -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');
});
});

View file

@ -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));

View file

@ -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}

View file

@ -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>

View file

@ -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>

View file

@ -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>

View file

@ -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>

View file

@ -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"

View file

@ -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"

View file

@ -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"

View file

@ -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>

View file

@ -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>

View file

@ -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: [] };

View file

@ -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) =>

View file

@ -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. */

View file

@ -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,

View file

@ -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);
});
});

View file

@ -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);

View file

@ -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);
});
});

View file

@ -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));

View file

@ -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');
});
});

View file

@ -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;
};

View file

@ -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 };
};

View file

@ -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>>;

View file

@ -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);
});
});

View file

@ -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;

View file

@ -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>>;

View file

@ -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)[] = [];

View file

@ -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();

View file

@ -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');
});
});

View file

@ -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';

View file

@ -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"

View file

@ -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"

View file

@ -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"

View file

@ -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>

View file

@ -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>

View file

@ -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>

View file

@ -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>

View file

@ -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"

View file

@ -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"

View file

@ -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>

View file

@ -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"

View file

@ -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>

View file

@ -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>

View file

@ -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>

View file

@ -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())}
>

View file

@ -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)} />;
}

View file

@ -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);

View file

@ -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} />

View file

@ -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))

View file

@ -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.`
);
};

View file

@ -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';

View file

@ -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>
)}

View file

@ -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"

View file

@ -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"

View file

@ -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}

View file

@ -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"

View file

@ -66,7 +66,6 @@ import { useAutoDiscoveryInfo } from '../../hooks/useAutoDiscoveryInfo';
import { livekitSupport } from '../../hooks/useLivekitSupport';
import { StateEvent } from '../../../types/matrix/room';
import { webRTCSupported } from '../../utils/rtc';
import { PhoneHitSpread24 } from '../../styles/PhoneHit.css';
type RoomNavItemMenuProps = {
room: Room;
@ -230,7 +229,6 @@ function CallChatToggle() {
return (
<IconButton
className={PhoneHitSpread24}
onClick={() => setChat(!chat)}
aria-pressed={chat}
aria-label="Toggle Chat"
@ -438,7 +436,6 @@ export function RoomNavItem({
}
>
<IconButton
className={PhoneHitSpread24}
onClick={handleOpenMenu}
aria-pressed={!!menuAnchor}
aria-controls={`menu-${room.roomId}`}

View file

@ -17,7 +17,6 @@ import { Permissions } from './permissions';
import { RoomSettingsPage } from '../../state/roomSettings';
import { useRoom } from '../../hooks/useRoom';
import { DeveloperTools } from '../common-settings/developer-tools';
import { PhoneHit } from '../../styles/PhoneHit.css';
type RoomSettingsMenuItem = {
page: RoomSettingsPage;
@ -118,7 +117,7 @@ export function RoomSettings({ initialPage, requestClose }: RoomSettingsProps) {
</Box>
<Box shrink="No">
{screenSize === ScreenSize.Mobile && (
<IconButton className={PhoneHit} onClick={requestClose} variant="Background">
<IconButton onClick={requestClose} variant="Background">
<Icon src={Icons.Cross} />
</IconButton>
)}

View file

@ -15,7 +15,6 @@ import {
} from '../../common-settings/general';
import { useRoomCreators } from '../../../hooks/useRoomCreators';
import { useRoomPermissions } from '../../../hooks/useRoomPermissions';
import { PhoneHit } from '../../../styles/PhoneHit.css';
type GeneralProps = {
requestClose: () => void;
@ -36,7 +35,7 @@ export function General({ requestClose }: GeneralProps) {
</Text>
</Box>
<Box shrink="No">
<IconButton className={PhoneHit} onClick={requestClose} variant="Surface">
<IconButton onClick={requestClose} variant="Surface">
<Icon src={Icons.Cross} />
</IconButton>
</Box>

View file

@ -9,7 +9,6 @@ import { usePermissionGroups } from './usePermissionItems';
import { PermissionGroups, Powers, PowersEditor } from '../../common-settings/permissions';
import { useRoomCreators } from '../../../hooks/useRoomCreators';
import { useRoomPermissions } from '../../../hooks/useRoomPermissions';
import { PhoneHit } from '../../../styles/PhoneHit.css';
type PermissionsProps = {
requestClose: () => void;
@ -46,7 +45,7 @@ export function Permissions({ requestClose }: PermissionsProps) {
</Text>
</Box>
<Box shrink="No">
<IconButton className={PhoneHit} onClick={requestClose} variant="Surface">
<IconButton onClick={requestClose} variant="Surface">
<Icon src={Icons.Cross} />
</IconButton>
</Box>

View file

@ -6,7 +6,6 @@ import { Page, PageHeader } from '../../components/page';
import { callChatAtom } from '../../state/callEmbed';
import { RoomView } from './RoomView';
import { ScreenSize, useScreenSizeContext } from '../../hooks/useScreenSize';
import { PhoneHit } from '../../styles/PhoneHit.css';
export function CallChatView() {
const { eventId } = useParams();
@ -43,7 +42,6 @@ export function CallChatView() {
>
{(triggerRef) => (
<IconButton
className={PhoneHit}
ref={triggerRef}
variant="Surface"
onClick={handleClose}

View file

@ -59,7 +59,6 @@ import { useSpaceOptionally } from '../../hooks/useSpace';
import { ContainerColor } from '../../styles/ContainerColor.css';
import { useFlattenPowerTagMembers, useGetMemberPowerTag } from '../../hooks/useMemberPowerTag';
import { useRoomCreators } from '../../hooks/useRoomCreators';
import { PhoneHit } from '../../styles/PhoneHit.css';
type MemberDrawerHeaderProps = {
room: Room;
@ -88,7 +87,6 @@ function MemberDrawerHeader({ room }: MemberDrawerHeaderProps) {
>
{(triggerRef) => (
<IconButton
className={PhoneHit}
ref={triggerRef}
variant="Background"
onClick={() => setPeopleDrawer(false)}
@ -361,7 +359,6 @@ export function MembersDrawer({ room, members }: MembersDrawerProps) {
<ScrollTopContainer scrollRef={scrollRef} anchorRef={scrollTopAnchorRef}>
<IconButton
className={PhoneHit}
onClick={() => virtualizer.scrollToOffset(0)}
variant="Surface"
radii="Pill"

View file

@ -116,7 +116,6 @@ import { useTheme } from '../../hooks/useTheme';
import { useRoomCreatorsTag } from '../../hooks/useRoomCreatorsTag';
import { usePowerLevelTags } from '../../hooks/usePowerLevelTags';
import { useComposingCheck } from '../../hooks/useComposingCheck';
import { PhoneHitSpread24, PhoneHitSpread32 } from '../../styles/PhoneHit.css';
interface RoomInputProps {
editor: Editor;
@ -606,7 +605,6 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
style={{ padding: `${config.space.S200} ${config.space.S300} 0` }}
>
<IconButton
className={PhoneHitSpread24}
onClick={() => setReplyDraft(undefined)}
variant="SurfaceVariant"
size="300"
@ -640,7 +638,6 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
}
before={
<IconButton
className={PhoneHitSpread32}
onClick={() => pickFile('*')}
variant="SurfaceVariant"
size="300"
@ -652,7 +649,6 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
after={
<>
<IconButton
className={PhoneHitSpread32}
variant="SurfaceVariant"
size="300"
radii="300"
@ -695,7 +691,6 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
>
{!hideStickerBtn && (
<IconButton
className={PhoneHitSpread32}
aria-pressed={emojiBoardTab === EmojiBoardTab.Sticker}
onClick={() => setEmojiBoardTab(EmojiBoardTab.Sticker)}
variant="SurfaceVariant"
@ -709,7 +704,6 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
</IconButton>
)}
<IconButton
className={PhoneHitSpread32}
ref={emojiBtnRef}
aria-pressed={
hideStickerBtn ? !!emojiBoardTab : emojiBoardTab === EmojiBoardTab.Emoji
@ -730,7 +724,6 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
)}
</UseStateProvider>
<IconButton
className={PhoneHitSpread32}
onClick={submit}
variant="SurfaceVariant"
size="300"

View file

@ -26,7 +26,7 @@ import { useRoom } from '../../hooks/useRoom';
import { AlbumView } from '../albums/AlbumView';
import * as albumCss from '../albums/AlbumView.css';
import { useIsFileZone } from '../albums/useAlbums';
import { ZoneView, zoneView } from '../albums/zoneView';
import { ZoneView, zoneView } from '../albums/buildAlbums';
const FN_KEYS_REGEX = /^F\d+$/;
const shouldFocusMessageField = (evt: KeyboardEvent): boolean => {

View file

@ -72,7 +72,6 @@ import { RoomSettingsPage } from '../../state/roomSettings';
import { useCallEmbed, useCallStart } from '../../hooks/useCallEmbed';
import { useLivekitSupport } from '../../hooks/useLivekitSupport';
import { webRTCSupported } from '../../utils/rtc';
import { PhoneHitSpread40 } from '../../styles/PhoneHit.css';
type RoomMenuProps = {
room: Room;
@ -337,7 +336,6 @@ function CallButton() {
>
{(triggerRef) => (
<IconButton
className={PhoneHitSpread40}
variant="Surface"
fill="None"
ref={triggerRef}
@ -457,7 +455,7 @@ export function RoomViewHeader({ callView }: { callView?: boolean }) {
<BackRouteHandler>
{(onBack) => (
<Box shrink="No" alignItems="Center">
<IconButton className={PhoneHitSpread40} fill="None" onClick={onBack}>
<IconButton fill="None" onClick={onBack}>
<Icon src={Icons.ArrowLeft} />
</IconButton>
</Box>
@ -534,7 +532,6 @@ export function RoomViewHeader({ callView }: { callView?: boolean }) {
>
{(triggerRef) => (
<IconButton
className={PhoneHitSpread40}
fill="None"
ref={triggerRef}
onClick={handleSearchClick}
@ -555,7 +552,6 @@ export function RoomViewHeader({ callView }: { callView?: boolean }) {
>
{(triggerRef) => (
<IconButton
className={PhoneHitSpread40}
fill="None"
style={{ position: 'relative' }}
onClick={handleOpenPinMenu}
@ -621,7 +617,6 @@ export function RoomViewHeader({ callView }: { callView?: boolean }) {
>
{(triggerRef) => (
<IconButton
className={PhoneHitSpread40}
fill="None"
ref={triggerRef}
onClick={handleMemberToggle}
@ -644,7 +639,6 @@ export function RoomViewHeader({ callView }: { callView?: boolean }) {
>
{(triggerRef) => (
<IconButton
className={PhoneHitSpread40}
fill="None"
onClick={handleOpenMenu}
ref={triggerRef}

View file

@ -10,7 +10,6 @@ import { getMxIdLocalPart } from '../../utils/matrix';
import * as css from './RoomViewTyping.css';
import { useMatrixClient } from '../../hooks/useMatrixClient';
import { useRoomTypingMember } from '../../hooks/useRoomTypingMembers';
import { PhoneHit } from '../../styles/PhoneHit.css';
export type RoomViewTypingProps = {
room: Room;
@ -113,7 +112,6 @@ export const RoomViewTyping = as<'div', RoomViewTypingProps>(
)}
</Text>
<IconButton
className={PhoneHit}
title="Drop Typing Status"
size="300"
radii="Pill"

View file

@ -31,7 +31,6 @@ import { getToday, getYesterday, timeDayMonthYear, timeHourMinute } from '../../
import { DatePicker, TimePicker } from '../../../components/time-date';
import { useSetting } from '../../../state/hooks/settings';
import { settingsAtom } from '../../../state/settings';
import { PhoneHit } from '../../../styles/PhoneHit.css';
type JumpToTimeProps = {
onCancel: () => void;
@ -109,7 +108,7 @@ export function JumpToTime({ onCancel, onSubmit }: JumpToTimeProps) {
<Box grow="Yes">
<Text size="H4">Jump to Time</Text>
</Box>
<IconButton className={PhoneHit} size="300" onClick={onCancel} radii="300">
<IconButton size="300" onClick={onCancel} radii="300">
<Icon src={Icons.Cross} />
</IconButton>
</Header>

View file

@ -61,8 +61,12 @@ import {
import { MessageLayout, MessageSpacing, settingsAtom } from '../../../state/settings';
import { useSetting } from '../../../state/hooks/settings';
import { PoseAvatar } from '../../../components/message/pose/PoseAvatar';
import { MINDS, mindOfSender } from '../../../components/message/pose/poses';
import { messagePose } from '../../../components/message/pose/sentiment';
import {
MINDS,
POSE_KEY,
mindOfSender,
resolvePose,
} from '../../../components/message/pose/poses';
import { useEntranceDelay } from '../../../components/message/pose/entrance';
import { useMatrixClient } from '../../../hooks/useMatrixClient';
import { useRecentEmoji } from '../../../hooks/useRecentEmoji';
@ -86,7 +90,6 @@ import colorMXID from '../../../../util/colorMXID';
import { useSkyInk } from '../../../hooks/useTheme';
import { userColorInk } from '../../scene/skyInk';
import { getPowerTagIconSrc } from '../../../hooks/useMemberPowerTag';
import { PhoneHitRoom26, PhoneHitSpread32 } from '../../../styles/PhoneHit.css';
export type ReactionHandler = (keyOrMxc: string, shortcode: string) => void;
@ -112,7 +115,7 @@ export const MessageQuickReactions = as<'div', MessageQuickReactionsProps>(
{recentEmojis.map((emoji) => (
<IconButton
key={emoji.unicode}
className={classNames(css.MessageQuickReaction, PhoneHitSpread32)}
className={css.MessageQuickReaction}
size="300"
variant="SurfaceVariant"
radii="Pill"
@ -461,7 +464,6 @@ export const MessageDeleteItem = as<
<Text size="H4">Delete Message</Text>
</Box>
<IconButton
className={PhoneHitSpread32}
size="300"
onClick={handleClose}
radii="300"
@ -596,7 +598,6 @@ export const MessageReportItem = as<
<Text size="H4">Report Message</Text>
</Box>
<IconButton
className={PhoneHitSpread32}
size="300"
onClick={handleClose}
radii="300"
@ -847,7 +848,7 @@ export const Message = as<'div', MessageProps>(
const poseJSX = !collapse && mind && (
<PoseAvatar
mind={mind}
pose={messagePose(mind, mEvent.getContent())}
pose={resolvePose(mind, mEvent.getContent()[POSE_KEY])}
userId={senderId}
alt={poseAlt}
enter={enterDelay !== undefined}
@ -961,7 +962,6 @@ export const Message = as<'div', MessageProps>(
}
>
<IconButton
className={PhoneHitRoom26}
onClick={handleOpenEmojiBoard}
variant="SurfaceVariant"
size="300"
@ -973,7 +973,6 @@ export const Message = as<'div', MessageProps>(
</PopOut>
)}
<IconButton
className={PhoneHitRoom26}
onClick={onReplyClick}
data-event-id={mEvent.getId()}
variant="SurfaceVariant"
@ -984,7 +983,6 @@ export const Message = as<'div', MessageProps>(
</IconButton>
{!isThreadedMessage && (
<IconButton
className={PhoneHitRoom26}
onClick={(ev) => onReplyClick(ev, true)}
data-event-id={mEvent.getId()}
variant="SurfaceVariant"
@ -996,7 +994,6 @@ export const Message = as<'div', MessageProps>(
)}
{canEditEvent(mx, mEvent) && onEditId && (
<IconButton
className={PhoneHitRoom26}
onClick={() => onEditId(mEvent.getId())}
variant="SurfaceVariant"
size="300"
@ -1162,7 +1159,6 @@ export const Message = as<'div', MessageProps>(
}
>
<IconButton
className={PhoneHitRoom26}
variant="SurfaceVariant"
size="300"
radii="300"
@ -1336,7 +1332,6 @@ export const Event = as<'div', EventProps>(
}
>
<IconButton
className={PhoneHitRoom26}
variant="SurfaceVariant"
size="300"
radii="300"

View file

@ -54,7 +54,6 @@ import { useMatrixClient } from '../../../hooks/useMatrixClient';
import { getEditedEvent, getMentionContent, trimReplyFromFormattedBody } from '../../../utils/room';
import { mobileOrTablet } from '../../../utils/user-agent';
import { useComposingCheck } from '../../../hooks/useComposingCheck';
import { PhoneHitSpread32 } from '../../../styles/PhoneHit.css';
type MessageEditorProps = {
roomId: string;
@ -290,7 +289,6 @@ export const MessageEditor = as<'div', MessageEditorProps>(
</Box>
<Box gap="Inherit">
<IconButton
className={PhoneHitSpread32}
variant="SurfaceVariant"
size="300"
radii="300"
@ -324,7 +322,6 @@ export const MessageEditor = as<'div', MessageEditorProps>(
}
>
<IconButton
className={PhoneHitSpread32}
aria-pressed={anchor !== undefined}
onClick={
((evt) =>

View file

@ -1,5 +1,7 @@
import { style } from '@vanilla-extract/css';
import { globalStyle, style } from '@vanilla-extract/css';
import { DefaultReset, config, toRem } from 'folds';
import { ICON_BUTTON_CLASS } from '../../../../phoneGlyph.css';
import { MOBILE_BREAKPOINT } from '../../../hooks/useScreenSize';
export const MessageBase = style({
position: 'relative',
@ -24,6 +26,10 @@ export const MessageOptionsBar = style([
},
]);
globalStyle(`${MessageOptionsBar} .${ICON_BUTTON_CLASS}`, {
'@media': { [`screen and (max-width: ${MOBILE_BREAKPOINT}px)`]: { margin: 9 } },
});
export const BubbleAvatarBase = style({
paddingTop: 0,
});

View file

@ -28,7 +28,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 ReactionViewerProps = {
room: Room;
@ -101,7 +100,7 @@ export const ReactionViewer = as<'div', ReactionViewerProps>(
<Box grow="Yes">
<Text size="H3" truncate>{`Reacted with :${selectedShortcode}:`}</Text>
</Box>
<IconButton className={PhoneHit} size="300" onClick={requestClose}>
<IconButton size="300" onClick={requestClose}>
<Icon src={Icons.Cross} />
</IconButton>
</Header>

View file

@ -86,7 +86,6 @@ import {
useGetMemberPowerTag,
} from '../../../hooks/useMemberPowerTag';
import { useRoomCreatorsTag } from '../../../hooks/useRoomCreatorsTag';
import { PhoneHit, PhoneHitSpread26 } from '../../../styles/PhoneHit.css';
type PinnedMessageProps = {
room: Room;
@ -147,7 +146,6 @@ function PinnedMessage({
</Chip>
{canPinEvent && (
<IconButton
className={PhoneHitSpread26}
data-event-id={eventId}
variant="Secondary"
size="300"
@ -459,7 +457,7 @@ export const RoomPinMenu = forwardRef<HTMLDivElement, RoomPinMenuProps>(
<Text size="H5">Pinned Messages</Text>
</Box>
<Box shrink="No">
<IconButton className={PhoneHit} size="300" onClick={requestClose} radii="300">
<IconButton size="300" onClick={requestClose} radii="300">
<Icon src={Icons.Cross} size="400" />
</IconButton>
</Box>

View file

@ -1,6 +1,5 @@
import React from 'react';
import { Icon, IconButton, Icons } from 'folds';
import { PhoneHit } from '../../styles/PhoneHit.css';
import { useSceneViewOffered } from '../../hooks/useSceneView';
import { loadSceneView, openSceneView } from './sceneView';
@ -17,7 +16,6 @@ export function SceneViewEntry() {
};
return (
<IconButton
className={PhoneHit}
variant="Background"
aria-label="Scene view"
title="Scene view"

View file

@ -1,5 +1,4 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { PhoneHit } from '../../styles/PhoneHit.css';
import { SceneViewHost, SceneViewLoading } from './SceneViewHost';
// The hooks are held still (view/SceneView.test.tsx): the element tree is read, effects are kept and run by the test.
@ -62,9 +61,8 @@ afterEach(() => {
});
describe('the view while its code loads', () => {
it('shows a Return that closes the view, with the phone tap target', () => {
it('shows a Return that closes the view', () => {
const ret = walk(SceneViewLoading()).find((e) => e.props?.['aria-label'] === 'Return');
expect(String(ret?.props?.className)).toContain(PhoneHit);
(ret?.props?.onClick as () => void)();
expect(held.closed).toBe(1);
});

View file

@ -1,7 +1,6 @@
import React, { ComponentType, useEffect, useState } from 'react';
import { createPortal } from 'react-dom';
import { Icon, IconButton, Icons } from 'folds';
import { PhoneHit } from '../../styles/PhoneHit.css';
import { useSceneViewOffered, useSceneViewState } from '../../hooks/useSceneView';
import { closeSceneView, loadSceneViewOrClose, restoreEntryFocus } from './sceneView';
import * as css from './sceneShell.css';
@ -23,7 +22,7 @@ export function SceneViewLoading() {
}, []);
return (
<IconButton
className={`${PhoneHit} ${css.LoadingReturn}`}
className={css.LoadingReturn}
variant="Background"
aria-label="Return"
title="Return"

View file

@ -2,7 +2,6 @@ import React, { useEffect, useRef } from 'react';
import { Box, Icon, IconButton, Icons, Text } from 'folds';
import { useDrawnPlace, useSkyChoice, useSkyMinute } from '../../../hooks/useSkyState';
import { usePlaceList } from '../../../hooks/useSceneView';
import { PhoneHit } from '../../../styles/PhoneHit.css';
import { LINES_CREDIT, STARS_CREDIT, terrainCredit } from '../ridge/credits';
import type { RidgeManifest, PlaceListing } from '../ridge/manifest';
import { localMinutes, momentFor } from '../ridge/skyMoment';
@ -74,7 +73,6 @@ export function PlaceCarousel({
return (
<Box className={css.Carousel} role="group" aria-label="Places" aria-roledescription="carousel">
<IconButton
className={PhoneHit}
variant="Background"
size="300"
aria-label="Previous place"
@ -110,7 +108,6 @@ export function PlaceCarousel({
))}
</div>
<IconButton
className={PhoneHit}
variant="Background"
size="300"
aria-label="Next place"

Some files were not shown because too many files have changed in this diff Show more