diff --git a/src/app/components/event-readers/EventReaders.tsx b/src/app/components/event-readers/EventReaders.tsx
index c7900237..72b188ce 100644
--- a/src/app/components/event-readers/EventReaders.tsx
+++ b/src/app/components/event-readers/EventReaders.tsx
@@ -24,6 +24,7 @@ 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;
@@ -52,7 +53,7 @@ export const EventReaders = as<'div', EventReadersProps>(
Seen by
-
+
diff --git a/src/app/components/invite-user-prompt/InviteUserPrompt.tsx b/src/app/components/invite-user-prompt/InviteUserPrompt.tsx
index ddac0576..a503fe13 100644
--- a/src/app/components/invite-user-prompt/InviteUserPrompt.tsx
+++ b/src/app/components/invite-user-prompt/InviteUserPrompt.tsx
@@ -42,6 +42,7 @@ 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,
@@ -173,7 +174,7 @@ export function InviteUserPrompt({ room, requestClose }: InviteUserProps) {
-
+
diff --git a/src/app/components/join-address-prompt/JoinAddressPrompt.tsx b/src/app/components/join-address-prompt/JoinAddressPrompt.tsx
index 50a89418..ffd5241c 100644
--- a/src/app/components/join-address-prompt/JoinAddressPrompt.tsx
+++ b/src/app/components/join-address-prompt/JoinAddressPrompt.tsx
@@ -20,6 +20,7 @@ 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;
@@ -82,7 +83,7 @@ export function JoinAddressPrompt({ onOpen, onCancel }: JoinAddressProps) {
Join with Address
-
+
diff --git a/src/app/components/leave-room-prompt/LeaveRoomPrompt.tsx b/src/app/components/leave-room-prompt/LeaveRoomPrompt.tsx
index 217491e6..832dd59d 100644
--- a/src/app/components/leave-room-prompt/LeaveRoomPrompt.tsx
+++ b/src/app/components/leave-room-prompt/LeaveRoomPrompt.tsx
@@ -20,6 +20,7 @@ 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;
@@ -68,7 +69,7 @@ export function LeaveRoomPrompt({ roomId, onDone, onCancel }: LeaveRoomPromptPro
Leave Room
-
+
diff --git a/src/app/components/leave-space-prompt/LeaveSpacePrompt.tsx b/src/app/components/leave-space-prompt/LeaveSpacePrompt.tsx
index 8709b942..6c75ef99 100644
--- a/src/app/components/leave-space-prompt/LeaveSpacePrompt.tsx
+++ b/src/app/components/leave-space-prompt/LeaveSpacePrompt.tsx
@@ -20,6 +20,7 @@ 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;
@@ -68,7 +69,7 @@ export function LeaveSpacePrompt({ roomId, onDone, onCancel }: LeaveSpacePromptP
Leave Space
-
+
diff --git a/src/app/components/room-topic-viewer/RoomTopicViewer.tsx b/src/app/components/room-topic-viewer/RoomTopicViewer.tsx
index 52128772..0d091e7e 100644
--- a/src/app/components/room-topic-viewer/RoomTopicViewer.tsx
+++ b/src/app/components/room-topic-viewer/RoomTopicViewer.tsx
@@ -4,6 +4,7 @@ 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',
@@ -26,7 +27,7 @@ export const RoomTopicViewer = as<
{name}
-
+
diff --git a/src/app/components/user-profile/PowerChip.tsx b/src/app/components/user-profile/PowerChip.tsx
index a6758300..d3e9cf28 100644
--- a/src/app/components/user-profile/PowerChip.tsx
+++ b/src/app/components/user-profile/PowerChip.tsx
@@ -43,6 +43,7 @@ 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;
@@ -70,7 +71,7 @@ function SelfDemoteAlert({ power, onCancel, onChange }: SelfDemoteAlertProps) {
Self Demotion
-
+
@@ -120,7 +121,7 @@ function SharedPowerAlert({ power, onCancel, onChange }: SharedPowerAlertProps)
Shared Power
-
+
diff --git a/src/app/features/add-existing/AddExisting.tsx b/src/app/features/add-existing/AddExisting.tsx
index d100096b..a57a6b10 100644
--- a/src/app/features/add-existing/AddExisting.tsx
+++ b/src/app/features/add-existing/AddExisting.tsx
@@ -54,6 +54,7 @@ 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,
@@ -201,7 +202,7 @@ export function AddExistingModal({ parentId, space, requestClose }: AddExistingM
Add Existing
-
+
diff --git a/src/app/features/call-status/CallControl.tsx b/src/app/features/call-status/CallControl.tsx
index 3cf38b1f..d63f8709 100644
--- a/src/app/features/call-status/CallControl.tsx
+++ b/src/app/features/call-status/CallControl.tsx
@@ -5,6 +5,7 @@ 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;
@@ -26,6 +27,7 @@ function MicrophoneButton({ enabled, onToggle, disabled }: MicrophoneButtonProps
>
{(anchorRef) => (
{(anchorRef) => (
{(anchorRef) => (
{(anchorRef) => (
{(anchorRef) => (
{(anchorRef) => (
{(anchorRef) => (
{(anchorRef) => (
{(anchorRef) => (
-
+
diff --git a/src/app/features/create-space/CreateSpaceModal.tsx b/src/app/features/create-space/CreateSpaceModal.tsx
index c1bc6898..faa53b25 100644
--- a/src/app/features/create-space/CreateSpaceModal.tsx
+++ b/src/app/features/create-space/CreateSpaceModal.tsx
@@ -23,6 +23,7 @@ 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;
@@ -61,7 +62,7 @@ function CreateSpaceModal({ state }: CreateSpaceModalProps) {
New Space
-
+
diff --git a/src/app/features/settings/Settings.tsx b/src/app/features/settings/Settings.tsx
index 5e1a20f4..6c91bc9d 100644
--- a/src/app/features/settings/Settings.tsx
+++ b/src/app/features/settings/Settings.tsx
@@ -33,6 +33,7 @@ import { About } from './about';
import { UseStateProvider } from '../../components/UseStateProvider';
import { stopPropagation } from '../../utils/keyboard';
import { LogoutDialog } from '../../components/LogoutDialog';
+import { PhoneHit } from '../../styles/PhoneHit.css';
export enum SettingsPages {
GeneralPage,
@@ -141,7 +142,7 @@ export function Settings({ initialPage, requestClose }: SettingsProps) {
{screenSize === ScreenSize.Mobile && (
-
+
)}
diff --git a/src/app/features/settings/about/About.tsx b/src/app/features/settings/about/About.tsx
index 9ec74305..19407bdf 100644
--- a/src/app/features/settings/about/About.tsx
+++ b/src/app/features/settings/about/About.tsx
@@ -8,6 +8,7 @@ import { LogoMark } from '../../../components/logo/logoMark.css';
import RatatoskrSVG from '../../../../../public/res/svg/ratatoskr.svg';
import { clearCacheAndReload } from '../../../../client/initMatrix';
import { useMatrixClient } from '../../../hooks/useMatrixClient';
+import { PhoneHit } from '../../../styles/PhoneHit.css';
type AboutProps = {
requestClose: () => void;
@@ -25,7 +26,7 @@ export function About({ requestClose }: AboutProps) {
-
+
diff --git a/src/app/features/settings/account/Account.tsx b/src/app/features/settings/account/Account.tsx
index c4b56e47..77ee8671 100644
--- a/src/app/features/settings/account/Account.tsx
+++ b/src/app/features/settings/account/Account.tsx
@@ -5,6 +5,7 @@ import { MatrixId } from './MatrixId';
import { Profile } from './Profile';
import { ContactInformation } from './ContactInfo';
import { IgnoredUserList } from './IgnoredUserList';
+import { PhoneHit } from '../../../styles/PhoneHit.css';
type AccountProps = {
requestClose: () => void;
@@ -20,7 +21,7 @@ export function Account({ requestClose }: AccountProps) {
-
+
diff --git a/src/app/features/settings/developer-tools/DevelopTools.tsx b/src/app/features/settings/developer-tools/DevelopTools.tsx
index a3f04567..7203fdc5 100644
--- a/src/app/features/settings/developer-tools/DevelopTools.tsx
+++ b/src/app/features/settings/developer-tools/DevelopTools.tsx
@@ -13,6 +13,7 @@ import {
} from '../../../components/AccountDataEditor';
import { copyToClipboard } from '../../../utils/dom';
import { AccountData } from './AccountData';
+import { PhoneHit } from '../../../styles/PhoneHit.css';
type DeveloperToolsProps = {
requestClose: () => void;
@@ -51,7 +52,7 @@ export function DeveloperTools({ requestClose }: DeveloperToolsProps) {
-
+
diff --git a/src/app/features/settings/devices/Devices.tsx b/src/app/features/settings/devices/Devices.tsx
index c957ab31..9e5821ba 100644
--- a/src/app/features/settings/devices/Devices.tsx
+++ b/src/app/features/settings/devices/Devices.tsx
@@ -26,6 +26,7 @@ import {
} from '../../../hooks/useSecretStorage';
import { useCrossSigningActive } from '../../../hooks/useCrossSigning';
import { BackupRestoreTile } from '../../../components/BackupRestore';
+import { PhoneHit } from '../../../styles/PhoneHit.css';
function DevicesPlaceholder() {
return (
@@ -74,7 +75,7 @@ export function Devices({ requestClose }: DevicesProps) {
-
+
diff --git a/src/app/features/settings/emojis-stickers/EmojisStickers.tsx b/src/app/features/settings/emojis-stickers/EmojisStickers.tsx
index 93715120..2c2193a9 100644
--- a/src/app/features/settings/emojis-stickers/EmojisStickers.tsx
+++ b/src/app/features/settings/emojis-stickers/EmojisStickers.tsx
@@ -5,6 +5,7 @@ import { GlobalPacks } from './GlobalPacks';
import { UserPack } from './UserPack';
import { ImagePack } from '../../../plugins/custom-emoji';
import { ImagePackView } from '../../../components/image-pack-view';
+import { PhoneHit } from '../../../styles/PhoneHit.css';
type EmojisStickersProps = {
requestClose: () => void;
@@ -30,7 +31,7 @@ export function EmojisStickers({ requestClose }: EmojisStickersProps) {
-
+
diff --git a/src/app/features/settings/emojis-stickers/GlobalPacks.tsx b/src/app/features/settings/emojis-stickers/GlobalPacks.tsx
index a9288728..38647b13 100644
--- a/src/app/features/settings/emojis-stickers/GlobalPacks.tsx
+++ b/src/app/features/settings/emojis-stickers/GlobalPacks.tsx
@@ -43,6 +43,7 @@ import { allRoomsAtom } from '../../../state/room-list/roomList';
import { AccountDataEvent } from '../../../../types/matrix/accountData';
import { AsyncStatus, useAsyncCallback } from '../../../hooks/useAsyncCallback';
import { stopPropagation } from '../../../utils/keyboard';
+import { PhoneHit } from '../../../styles/PhoneHit.css';
function GlobalPackSelector({
packs,
@@ -368,6 +369,7 @@ export function GlobalPacks({ onViewPack }: GlobalPacksProps) {
{removed ? (
) : (
;
@@ -497,6 +498,7 @@ function DateHint({ hasChanges, handleReset }: DateHintProps) {
>
{hasChanges ? (
) : (
-
+
diff --git a/src/app/features/settings/notifications/KeywordMessages.tsx b/src/app/features/settings/notifications/KeywordMessages.tsx
index 7f84d607..b77cae21 100644
--- a/src/app/features/settings/notifications/KeywordMessages.tsx
+++ b/src/app/features/settings/notifications/KeywordMessages.tsx
@@ -15,6 +15,7 @@ import {
} from '../../../hooks/useNotificationMode';
import { NotificationModeSwitcher } from './NotificationModeSwitcher';
import { AsyncStatus, useAsyncCallback } from '../../../hooks/useAsyncCallback';
+import { PhoneHit } from '../../../styles/PhoneHit.css';
const NOTIFY_MODE_OPS: NotificationModeOptions = {
highlight: true,
@@ -75,6 +76,7 @@ function KeywordInput() {
keyword &&
!addingKeyword && (
+
{removing ? : }
);
diff --git a/src/app/features/settings/notifications/Notifications.tsx b/src/app/features/settings/notifications/Notifications.tsx
index 095a9bba..61af1a09 100644
--- a/src/app/features/settings/notifications/Notifications.tsx
+++ b/src/app/features/settings/notifications/Notifications.tsx
@@ -8,6 +8,7 @@ import { KeywordMessagesNotifications } from './KeywordMessages';
import { SequenceCard } from '../../../components/sequence-card';
import { SequenceCardStyle } from '../styles.css';
import { SettingTile } from '../../../components/setting-tile';
+import { PhoneHit } from '../../../styles/PhoneHit.css';
type NotificationsProps = {
requestClose: () => void;
@@ -23,7 +24,7 @@ export function Notifications({ requestClose }: NotificationsProps) {
-
+
diff --git a/src/app/phoneHit.call.test.ts b/src/app/phoneHit.call.test.ts
new file mode 100644
index 00000000..56971b05
--- /dev/null
+++ b/src/app/phoneHit.call.test.ts
@@ -0,0 +1,15 @@
+import { describe, it } from 'vitest';
+import { expectPhoneHitClasses, expectSizeTie } from './phoneHitTestKit';
+
+// Every IconButton of the call bars carries the phone hit-area variant of its drawn size, in source order
+// (mic, sound, video, share, chat; the menu button; the call-status mic, sound, video, share).
+describe('icon buttons in the call controls', () => {
+ it.each([
+ ['features/call/Controls.tsx', Array(5).fill('PhoneHitSpread40')],
+ ['features/call/CallControls.tsx', ['PhoneHitSpread40']],
+ ['features/call-status/CallControl.tsx', Array(4).fill('PhoneHitSpread26')],
+ ])('%s', (file, want) => {
+ expectPhoneHitClasses(file as string, want as string[]);
+ expectSizeTie(file as string);
+ });
+});
diff --git a/src/app/phoneHit.dialogs.test.ts b/src/app/phoneHit.dialogs.test.ts
new file mode 100644
index 00000000..8b3416a5
--- /dev/null
+++ b/src/app/phoneHit.dialogs.test.ts
@@ -0,0 +1,28 @@
+import { describe, it } from 'vitest';
+import { expectPhoneHitClasses, expectSizeTie } from './phoneHitTestKit';
+
+// Dialog and prompt close buttons: each is a 32 px button (24 px Icon + 8 px padding) alone at the end of a
+// header whose title is not tappable, so the plain PhoneHit; no neighbour to spread from, no clipping container.
+describe('icon buttons in dialogs and prompts', () => {
+ const expected: Record = {
+ 'features/create-space/CreateSpaceModal.tsx': ['PhoneHit'],
+ 'features/create-room/CreateRoomModal.tsx': ['PhoneHit'],
+ 'features/add-existing/AddExisting.tsx': ['PhoneHit'],
+ 'components/room-topic-viewer/RoomTopicViewer.tsx': ['PhoneHit'],
+ 'components/leave-room-prompt/LeaveRoomPrompt.tsx': ['PhoneHit'],
+ 'components/leave-space-prompt/LeaveSpacePrompt.tsx': ['PhoneHit'],
+ 'components/event-readers/EventReaders.tsx': ['PhoneHit'],
+ 'components/invite-user-prompt/InviteUserPrompt.tsx': ['PhoneHit'],
+ 'components/join-address-prompt/JoinAddressPrompt.tsx': ['PhoneHit'], // join cancel
+ 'components/user-profile/PowerChip.tsx': ['PhoneHit', 'PhoneHit'], // self demotion, shared power
+ };
+
+ it.each(Object.entries(expected))(
+ '%s: each IconButton carries its own PhoneHit class',
+ (file, want) => expectPhoneHitClasses(file, want)
+ );
+
+ it.each(Object.keys(expected))('%s: a sized variant matches the drawn size', (file) =>
+ expectSizeTie(file)
+ );
+});
diff --git a/src/app/phoneHit.settingsA.test.ts b/src/app/phoneHit.settingsA.test.ts
new file mode 100644
index 00000000..37f1f3c2
--- /dev/null
+++ b/src/app/phoneHit.settingsA.test.ts
@@ -0,0 +1,29 @@
+import { describe, it } from 'vitest';
+import { expectPhoneHitClasses, expectSizeTie } from './phoneHitTestKit';
+
+describe('icon buttons in settings A', () => {
+ // The class each IconButton must carry, in source order. Every one is alone in its row (a header close next to
+ // non-tappable title text, an input slot, or a list tile beside a non-tappable Avatar), so the plain PhoneHit.
+ const expected: Record = {
+ 'features/settings/developer-tools/DevelopTools.tsx': ['PhoneHit'], // header close, 40 px
+ 'features/settings/notifications/Notifications.tsx': ['PhoneHit'], // header close, 40 px
+ 'features/settings/notifications/KeywordMessages.tsx': ['PhoneHit', 'PhoneHit'], // input reset, remove: 26 px, alone
+ 'features/settings/emojis-stickers/EmojisStickers.tsx': ['PhoneHit'], // header close, 40 px
+ 'features/settings/emojis-stickers/GlobalPacks.tsx': ['PhoneHit', 'PhoneHit'], // undo / remove, a ternary pair, 26 px
+ 'features/settings/Settings.tsx': ['PhoneHit'], // mobile-only header close, 40 px
+ 'features/settings/about/About.tsx': ['PhoneHit'], // header close, 40 px
+ 'features/settings/general/General.tsx': ['PhoneHit', 'PhoneHit', 'PhoneHit'], // reset / info (ternary), header close
+ 'features/settings/account/Account.tsx': ['PhoneHit'], // header close, 40 px
+ 'features/settings/devices/Devices.tsx': ['PhoneHit'], // header close, 40 px
+ };
+
+ it.each(Object.entries(expected))('%s carries the right hit-area class', (file, want) => {
+ expectPhoneHitClasses(file, want);
+ });
+
+ // Plain PhoneHit has no size to tie, so nothing is allow-listed; the check still fails an allow-list entry
+ // or a sized variant that disagrees with the drawn size if one is added later.
+ it.each(Object.keys(expected))('%s ties a sized variant to the drawn size', (file) => {
+ expectSizeTie(file);
+ });
+});
diff --git a/src/app/phoneHitTestKit.test.ts b/src/app/phoneHitTestKit.test.ts
index 92f1b23f..a77a2e27 100644
--- a/src/app/phoneHitTestKit.test.ts
+++ b/src/app/phoneHitTestKit.test.ts
@@ -1,5 +1,14 @@
import { describe, expect, it } from 'vitest';
-import { drawnPx, expectSizeTie, iconButtons } from './phoneHitTestKit';
+import { mkdtempSync, rmSync, writeFileSync } from 'fs';
+import { tmpdir } from 'os';
+import { relative } from 'path';
+import {
+ drawnPx,
+ expectPhoneHitClasses,
+ expectSizeTie,
+ iconButtons,
+ phoneHitOf,
+} from './phoneHitTestKit';
describe('phone hit test kit', () => {
it('reads {
@@ -38,4 +47,108 @@ describe('phone hit test kit', () => {
it('fails a file with no IconButton, which would otherwise pass vacuously', () => {
expect(() => expectSizeTie('styles/PhoneHit.css.ts')).toThrow(/no IconButton/);
});
+
+ describe('phoneHitOf reads the imported class off the AST, applied unconditionally', () => {
+ const tag = (expr: string) => ``;
+ const ok = (expr: string, name: string) => expect(phoneHitOf(tag(expr))).toBe(name);
+ const no = (expr: string) => expect(phoneHitOf(tag(expr))).toBeNull();
+
+ it('accepts the bare identifier and merges that always include it', () => {
+ ok('PhoneHitSpread26', 'PhoneHitSpread26');
+ ok('classNames(PhoneHitRoom36, css.other)', 'PhoneHitRoom36');
+ ok('clsx(css.a, { [css.b]: on }, PhoneHit)', 'PhoneHit');
+ ok('cx(PhoneHit)', 'PhoneHit');
+ ok('`${PhoneHit} ${css.other}`', 'PhoneHit');
+ ok('classNames(/* PhoneHit */ PhoneHit)', 'PhoneHit');
+ });
+
+ it('rejects the name as a string, a concatenation or a comment', () => {
+ no("'PhoneHitSpread26'");
+ no('`PhoneHitSpread26`');
+ no('"PhoneHitSpread26" + "x"');
+ no("'PhoneHit' + 'Spread26'");
+ no('/* PhoneHit */ undefined');
+ no('css.a // PhoneHit');
+ });
+
+ it('rejects a conditionally applied name', () => {
+ no('cond ? PhoneHitSpread26 : undefined');
+ no('cond && PhoneHitSpread26');
+ no('cond || PhoneHitSpread26');
+ no('maybe ?? PhoneHitSpread26');
+ no("classNames(cond ? PhoneHit : '', css.a)");
+ no('classNames(PhoneHit, cond && PhoneHit)');
+ });
+
+ it('rejects every other expression shape the name can hide in', () => {
+ no('classNames({ PhoneHit: on })');
+ no('clsx({ [PhoneHit]: on })');
+ no('`${`${PhoneHit}`}`');
+ no('typeof PhoneHit');
+ no("(PhoneHit = 'x')");
+ no('(PhoneHit, css.a)');
+ no('(PhoneHit)');
+ no('() => PhoneHit');
+ no('PhoneHit.foo');
+ no('other.PhoneHit');
+ no('classNames(css.a, [PhoneHit])');
+ no('wrap(PhoneHit)');
+ no('PhoneHitSpread26é');
+ no('`${css.a}`');
+ });
+
+ it('rejects a tag without className, with two, or with a non-expression one', () => {
+ expect(phoneHitOf('')).toBeNull();
+ expect(phoneHitOf('')).toBeNull();
+ expect(phoneHitOf('')).toBeNull();
+ expect(phoneHitOf('')).toBe('PhoneHit');
+ });
+
+ it('rejects a spread after className, which can override it, and accepts one before', () => {
+ expect(phoneHitOf('')).toBeNull();
+ expect(phoneHitOf('')).toBeNull();
+ expect(phoneHitOf('')).toBe('PhoneHit');
+ });
+
+ it('reads a className past braces inside strings', () => {
+ ok("classNames('{', PhoneHit)", 'PhoneHit');
+ });
+ });
+
+ describe('expectPhoneHitClasses', () => {
+ const check = (src: string, want: (string | null)[]) => {
+ const dir = mkdtempSync(`${tmpdir()}/phone-hit-kit-`);
+ try {
+ writeFileSync(`${dir}/Probe.tsx`, src);
+ expectPhoneHitClasses(relative(`${process.cwd()}/src/app`, `${dir}/Probe.tsx`), want);
+ } finally {
+ rmSync(dir, { recursive: true });
+ }
+ };
+ const imp = "import { PhoneHit, PhoneHitSpread26 } from '../../styles/PhoneHit.css';\n";
+ const src =
+ imp +
+ 'const A = () => (<>>);';
+
+ it('pins each button in order, null meaning no class', () => {
+ check(src, ['PhoneHit', 'PhoneHitSpread26', null]);
+ expect(() => check(src, ['PhoneHit', 'PhoneHit', null])).toThrow();
+ expect(() => check(src, ['PhoneHit', 'PhoneHitSpread26', 'PhoneHit'])).toThrow();
+ expect(() => check(src, ['PhoneHit', 'PhoneHitSpread26'])).toThrow();
+ });
+
+ it('fails a name that is not read from PhoneHit.css or is applied conditionally', () => {
+ const local = "const PhoneHit = 'x';\n";
+ expect(() => check(local, ['PhoneHit'])).toThrow();
+ expect(() => check(local, [null])).not.toThrow();
+ const cond = imp + '';
+ expect(() => check(cond, ['PhoneHit'])).toThrow();
+ const aliased =
+ "import { Other as PhoneHit } from '../../styles/PhoneHit.css';\n";
+ expect(() => check(aliased, ['PhoneHit'])).toThrow();
+ const wrongModule =
+ "import { PhoneHit } from './other';\n";
+ expect(() => check(wrongModule, ['PhoneHit'])).toThrow();
+ });
+ });
});
diff --git a/src/app/phoneHitTestKit.ts b/src/app/phoneHitTestKit.ts
index a29dcc22..896b917b 100644
--- a/src/app/phoneHitTestKit.ts
+++ b/src/app/phoneHitTestKit.ts
@@ -2,6 +2,7 @@
// group of IconButtons). Not a test file: it registers nothing, the test files call it.
import { readFileSync } from 'fs';
import { expect } from 'vitest';
+import ts from 'typescript';
import zlib from 'zlib';
import { compile, processVanillaFile } from '@vanilla-extract/integration';
@@ -72,36 +73,113 @@ const tagEnd = (src: string, from: number) => {
return j;
};
-/** Every outside any {} expression, and
- * what it wraps (empty when self-closing). */
+const tsx = (src: string) =>
+ ts.createSourceFile('source.tsx', src, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
+
+type Opening = ts.JsxOpeningElement | ts.JsxSelfClosingElement;
+
+/** Every IconButton element (not IconButtonX) of a parsed source, in source order. */
+const elements = (sf: ts.SourceFile) => {
+ const found: Opening[] = [];
+ const walk = (n: ts.Node) => {
+ if (
+ (ts.isJsxOpeningElement(n) || ts.isJsxSelfClosingElement(n)) &&
+ ts.isIdentifier(n.tagName) &&
+ n.tagName.text === 'IconButton'
+ )
+ found.push(n);
+ ts.forEachChild(n, walk);
+ };
+ walk(sf);
+ return found;
+};
+
+const bodyOf = (el: Opening) =>
+ ts.isJsxOpeningElement(el) && ts.isJsxElement(el.parent)
+ ? el.getSourceFile().text.slice(el.end, el.parent.closingElement.getStart())
+ : '';
+
+/** Every
- [...src.matchAll(//])/g)].map((m) => {
- const start = m.index ?? 0;
- const end = tagEnd(src, start);
- const tag = src.slice(start, end + 1);
- const close = src.indexOf('', end);
- return { tag, body: tag.endsWith('/>') || close === -1 ? '' : src.slice(end + 1, close) };
- });
+ elements(tsx(src)).map((el) => ({ tag: el.getText(), body: bodyOf(el) }));
export const iconButtonTags = (src: string) => iconButtons(src).map((b) => b.tag);
-const phoneHitOf = (tag: string) => tag.match(/className=\{[^}]*?\b(PhoneHit\w*)\b/)?.[1] ?? null;
-
-/** The class each IconButton must carry, in source order: the variant is chosen by the button's drawn size and
- * whether a clipping container or neighbours surround it, so a swapped variant is a wrong hit area. Also checks
- * the name is the one PhoneHit.css.ts exports, not a local of the same name. */
-export const expectPhoneHitClasses = (file: string, want: string[]) => {
- const src = readSource(file);
- expect(iconButtonTags(src).map(phoneHitOf)).toEqual(want);
- [...new Set(want)].forEach((name) =>
- expect(src).toMatch(
- new RegExp(
- `import \\{(?:[^}]*,)?\\s*${name}\\s*(?:,[^}]*)?\\} from '(\\.\\./)+styles/PhoneHit\\.css'`
- )
- )
+/** Local names the source imports from the PhoneHit.css module (as written, not aliased). */
+const importedHits = (sf: ts.SourceFile) =>
+ new Set(
+ sf.statements.flatMap((st) => {
+ const nb = ts.isImportDeclaration(st) ? st.importClause?.namedBindings : undefined;
+ return nb &&
+ ts.isNamedImports(nb) &&
+ ts.isStringLiteral((st as ts.ImportDeclaration).moduleSpecifier) &&
+ /^(\.\.\/)+styles\/PhoneHit\.css$/.test(
+ ((st as ts.ImportDeclaration).moduleSpecifier as ts.StringLiteral).text
+ )
+ ? nb.elements.filter((e) => !e.propertyName).map((e) => e.name.text)
+ : [];
+ })
);
+
+const MERGERS = new Set(['classNames', 'clsx', 'cx']);
+
+/** The PhoneHit* class an IconButton carries, or null. className must appear exactly once, with no props spread
+ * after it (a spread can override it at runtime), and its expression must be: the bare identifier; a classNames /
+ * clsx / cx call with it as a direct argument; or a template with it as a direct span. The identifier must occur
+ * nowhere else in the expression, so a key, a member, a closure, a conditional or a comma can never carry it. When
+ * `imported` is given, the identifier must also be a binding imported from the PhoneHit.css module. */
+const hitOf = (el: Opening, imported?: Set): string | null => {
+ const props = el.attributes.properties;
+ const at = props.flatMap((p, i) =>
+ ts.isJsxAttribute(p) && ts.isIdentifier(p.name) && p.name.text === 'className' ? [i] : []
+ );
+ if (at.length !== 1 || props.slice(at[0] + 1).some(ts.isJsxSpreadAttribute)) return null;
+ const attr = props[at[0]] as ts.JsxAttribute;
+ const expr =
+ attr.initializer && ts.isJsxExpression(attr.initializer) && attr.initializer.expression;
+ if (!expr) return null;
+ const isHit = (n: ts.Node): n is ts.Identifier =>
+ ts.isIdentifier(n) && /^PhoneHit\w*$/.test(n.text) && (!imported || imported.has(n.text));
+ let direct: ts.Node[] = [];
+ if (ts.isIdentifier(expr)) direct = [expr];
+ else if (
+ ts.isCallExpression(expr) &&
+ ts.isIdentifier(expr.expression) &&
+ MERGERS.has(expr.expression.text)
+ )
+ direct = [...expr.arguments];
+ else if (ts.isTemplateExpression(expr)) direct = expr.templateSpans.map((sp) => sp.expression);
+ const hits = direct.filter(isHit);
+ if (hits.length !== 1) return null;
+ let occurrences = 0;
+ const count = (n: ts.Node) => {
+ if (ts.isIdentifier(n) && n.text === hits[0].text) occurrences += 1;
+ ts.forEachChild(n, count);
+ };
+ count(expr);
+ return occurrences === 1 ? hits[0].text : null;
};
+/** The PhoneHit* class of one tag's text (see hitOf), without the import-binding check. */
+export const phoneHitOf = (tag: string) => {
+ const els = elements(tsx(tag.endsWith('/>') ? tag : `${tag}`));
+ return els.length === 1 ? hitOf(els[0]) : null;
+};
+
+/** The PhoneHit* class of each IconButton of a source, in source order; null when it has none or the name is not
+ * the one imported from PhoneHit.css. */
+const phoneHitClasses = (src: string) => {
+ const sf = tsx(src);
+ const imported = importedHits(sf);
+ return elements(sf).map((el) => hitOf(el, imported));
+};
+
+/** The class each IconButton must carry, in source order (null = must carry none): the variant is chosen by the
+ * button's drawn size and whether a clipping container or neighbours surround it, so a swapped variant is a wrong
+ * hit area. The name must also be the one PhoneHit.css exports, not a local of the same name. */
+export const expectPhoneHitClasses = (file: string, want: (string | null)[]) =>
+ expect(phoneHitClasses(readSource(file))).toEqual(want);
+
// IconButton `size` -> padding on each side, Icon `size` -> px (folds 2.7.2). Both default to 400.
const BUTTON_PAD: Record = { '300': 4, '400': 8, '500': 12, '600': 16 };
const ICON_PX: Record = {
@@ -147,10 +225,12 @@ export type SizeAllow = Record>;
export const expectSizeTie = (file: string, allow: SizeAllow = {}) => {
const allowed = allow[file] ?? {};
const seen = new Set();
- const buttons = iconButtons(readSource(file));
+ const src = readSource(file);
+ const buttons = iconButtons(src);
+ const classes = phoneHitClasses(src);
expect(buttons.length, `${file} has no IconButton`).toBeGreaterThan(0);
buttons.forEach(({ tag, body }, i) => {
- const variant = phoneHitOf(tag)?.match(/^PhoneHit(?:Spread|Room)(\d+)$/);
+ const variant = classes[i]?.match(/^PhoneHit(?:Spread|Room)(\d+)$/);
if (!variant) {
expect(allowed[i], `${file} #${i} is allow-listed but has no sized variant`).toBeUndefined();
return;