(feat): improved mobile notifications

(feat): add lint rules
(feat): improve markdown inline code box
This commit is contained in:
Alois 2026-08-05 21:41:55 +02:00
commit 4a841de073
Signed by: alois
SSH key fingerprint: SHA256:GBzT2DXvAuGV9XIV5W3WrzVpjU54FThmxHXdbz95J24
35 changed files with 777 additions and 287 deletions

View file

@ -17,22 +17,6 @@ type MediaShareStoreState = {
cameraSession: LocalMediaShareSession | null;
};
type MediaShareStoreSetState = (
updater:
| Partial<MediaShareStoreState>
| ((state: MediaShareStoreState) => Partial<MediaShareStoreState>),
) => void;
type MediaShareControllerOptions = {
room: Room;
getState: () => MediaShareStoreState;
setState: MediaShareStoreSetState;
getLocalParticipantId: () => number | null;
startWatching: (participantId: number) => void;
stopWatching: (participantId: number) => void;
syncParticipantState: () => void;
};
export function createMediaShareController({
room,
getState,
@ -41,7 +25,19 @@ export function createMediaShareController({
startWatching,
stopWatching,
syncParticipantState,
}: MediaShareControllerOptions) {
}: {
room: Room;
getState: () => MediaShareStoreState;
setState: (
updater:
| Partial<MediaShareStoreState>
| ((state: MediaShareStoreState) => Partial<MediaShareStoreState>),
) => void;
getLocalParticipantId: () => number | null;
startWatching: (participantId: number) => void;
stopWatching: (participantId: number) => void;
syncParticipantState: () => void;
}) {
function getSession(kind: MediaShareKind) {
return kind === "screen"
? getState().screenShareSession

View file

@ -8,32 +8,16 @@ import type {
MediaShareSource,
} from "./types";
type MobileMediaApi = {
startScreenShare: (includeAudio: boolean) => void;
stopScreenShare: () => void;
requestCameraPermission: () => void;
};
declare global {
interface Window {
tensaminMobileMedia?: MobileMediaApi;
tensaminMobileMedia?: {
startScreenShare: (includeAudio: boolean) => void;
stopScreenShare: () => void;
requestCameraPermission: () => void;
};
}
}
type FrameDetail = {
data: string;
mimeType: string;
width: number;
height: number;
};
type AudioDetail = {
data: string;
sampleRate: number;
channelCount: number;
encoding: "pcm16le";
};
function eventDetail<T>(event: Event): T {
return (event as CustomEvent<T>).detail;
}
@ -164,7 +148,12 @@ async function startMobileScreen(
};
const onFrame = (event: Event) => {
const detail = eventDetail<FrameDetail>(event);
const detail = eventDetail<{
data: string;
mimeType: string;
width: number;
height: number;
}>(event);
const image = new Image();
image.onload = () => {
if (canvas.width !== detail.width || canvas.height !== detail.height) {
@ -179,7 +168,14 @@ async function startMobileScreen(
};
const onAudio = (event: Event) => {
const bytes = decodeBase64(eventDetail<AudioDetail>(event).data);
const bytes = decodeBase64(
eventDetail<{
data: string;
sampleRate: number;
channelCount: number;
encoding: "pcm16le";
}>(event).data,
);
const samples = new Int16Array(
bytes.buffer,
bytes.byteOffset,

View file

@ -10,18 +10,19 @@ const SPEAKING_HANGTIME_MS = 500;
const ANALYSIS_INTERVAL_MS = 30;
const FFT_SIZE = 256;
type AnalyserEntry = {
source: MediaStreamAudioSourceNode;
analyser: AnalyserNode;
track: MediaStreamTrack;
originalTrack?: MediaStreamTrack;
lastSpeakingTime: number;
isSpeaking: boolean;
};
class SpeakingDetector {
private audioContext: AudioContext | null = null;
private entries = new Map<number, AnalyserEntry>();
private entries = new Map<
number,
{
source: MediaStreamAudioSourceNode;
analyser: AnalyserNode;
track: MediaStreamTrack;
originalTrack?: MediaStreamTrack;
lastSpeakingTime: number;
isSpeaking: boolean;
}
>();
private intervalId: ReturnType<typeof setInterval> | null = null;
private deaf = false;
private gateThresholdStart = -50;

View file

@ -1,12 +1,10 @@
import { create } from "zustand";
type SpeakingState = {
const useSpeakingState = create<{
speakingParticipantIds: Set<number>;
lastSpeakingParticipantId: number | null;
micGated: boolean;
};
const useSpeakingState = create<SpeakingState>(() => ({
}>(() => ({
speakingParticipantIds: new Set(),
lastSpeakingParticipantId: null,
micGated: false,

View file

@ -51,7 +51,6 @@ setLogExtension(
getLogger("tensamin"),
);
type CallState = "closed" | "closing" | "connecting" | "open" | "encrypting";
type CallView = "preview" | "focused" | "grid";
type ProtocolCallSecret = NonNullable<
z.infer<typeof mtp.CallInvite.response>["CallSecret"]
@ -63,18 +62,9 @@ type WrappedCallSecret = {
kemCiphertext: Uint8Array;
wrappingScheme: string;
};
type IncomingCallInvite = {
callId: string;
callSecret: WrappedCallSecret;
senderId: number;
};
type CurrentCallData =
(z.infer<typeof mtp.CallData.response> & { exists: boolean }) | null;
type NavigateFn = (options: {
to: string;
search?: Record<string, unknown>;
}) => Promise<void>;
type SendFn = (
type: string,
data: Record<string, unknown>,
@ -84,44 +74,15 @@ type GetUserFn = (userId: number) => Promise<{ PublicKey: string }>;
type RemoteVideoTrackSelector = Track.Kind | Track.Source;
type Runtime = {
navigate: NavigateFn;
navigate: (options: {
to: string;
search?: Record<string, unknown>;
}) => Promise<void>;
send: SendFn;
load: LoadFn;
getUser: GetUserFn;
};
type CallStore = {
state: CallState;
view: CallView;
invitedUserId: number | null;
callId: string | null;
incomingCallInvite: IncomingCallInvite | null;
callSecret: string | null;
livekitToken: string | null;
currentCallData: CurrentCallData;
deaf: boolean;
micEnabled: boolean;
cameraEnabled: boolean;
screenShareEnabled: boolean;
screenShareSession: LocalMediaShareSession | null;
cameraSession: LocalMediaShareSession | null;
disabledCameraParticipantIds: number[];
focusedParticipantId: number | null;
focusedParticipantType: "user" | "stream" | null;
usersInFocusedViewHidden: boolean;
watchedStreamParticipantIds: number[];
pendingWatchedParticipantIds: number[];
activeScreenShareParticipantIds: number[];
isEncrypted: boolean;
ownCallSecretInvitePending: boolean;
callIsFullscreen: boolean;
callIsPopout: boolean;
layoutVersion: number;
screenRef: React.RefObject<HTMLDivElement | null> | null;
runtime: Runtime | null;
lastFocusedParticipantId: number | null;
};
let _keyProvider: ExternalE2EEKeyProvider | null = null;
let _e2eeWorker: Worker | null = null;
let _room: Room | null = null;
@ -1195,7 +1156,41 @@ async function ensureNoiseFilter(
}
}
export const useCall = create<CallStore>(() => ({
export const useCall = create<{
state: "closed" | "closing" | "connecting" | "open" | "encrypting";
view: CallView;
invitedUserId: number | null;
callId: string | null;
incomingCallInvite: {
callId: string;
callSecret: WrappedCallSecret;
senderId: number;
} | null;
callSecret: string | null;
livekitToken: string | null;
currentCallData: CurrentCallData;
deaf: boolean;
micEnabled: boolean;
cameraEnabled: boolean;
screenShareEnabled: boolean;
screenShareSession: LocalMediaShareSession | null;
cameraSession: LocalMediaShareSession | null;
disabledCameraParticipantIds: number[];
focusedParticipantId: number | null;
focusedParticipantType: "user" | "stream" | null;
usersInFocusedViewHidden: boolean;
watchedStreamParticipantIds: number[];
pendingWatchedParticipantIds: number[];
activeScreenShareParticipantIds: number[];
isEncrypted: boolean;
ownCallSecretInvitePending: boolean;
callIsFullscreen: boolean;
callIsPopout: boolean;
layoutVersion: number;
screenRef: React.RefObject<HTMLDivElement | null> | null;
runtime: Runtime | null;
lastFocusedParticipantId: number | null;
}>(() => ({
state: "closed",
view: "preview",
invitedUserId: null,

View file

@ -34,35 +34,25 @@ function getColumnCount(width: number, itemCount: number) {
type KlipyKind = "gif" | "meme";
type KlipyMediaFile = {
url?: string;
width?: number;
height?: number;
};
type KlipyMediaFormats = Record<string, KlipyMediaFile | undefined>;
type KlipyItem = {
id: number | string;
title?: string;
file?: Record<string, KlipyMediaFormats | undefined>;
file?: Record<
string,
| Record<
string,
| {
url?: string;
width?: number;
height?: number;
}
| undefined
>
| undefined
>;
blur_preview?: string;
};
type KlipyPage = {
items: KlipyItem[];
currentPage: number;
hasNext: boolean;
};
type KlipyResponse = {
data?: {
data?: KlipyItem[];
current_page?: number;
has_next?: boolean;
};
};
type PickerMedia = {
key: React.Key;
url: string;
@ -105,7 +95,11 @@ async function fetchKlipyPage({
kind: KlipyKind;
page: number;
search: string;
}): Promise<KlipyPage> {
}): Promise<{
items: KlipyItem[];
currentPage: number;
hasNext: boolean;
}> {
const params = new URLSearchParams({
page: String(page),
per_page: String(pageSize),
@ -128,7 +122,13 @@ async function fetchKlipyPage({
throw new Error(`Klipy request failed with status ${response.status}`);
}
const body = (await response.json()) as KlipyResponse;
const body = (await response.json()) as {
data?: {
data?: KlipyItem[];
current_page?: number;
has_next?: boolean;
};
};
const data = body.data;
return {

View file

@ -66,6 +66,13 @@ export default function InputComponent({
return () => cancelAnimationFrame(frame);
}, [userId]);
useEffect(() => {
if (replyTo === undefined) return;
const frame = requestAnimationFrame(() => composerRef.current?.focus());
return () => cancelAnimationFrame(frame);
}, [replyTo]);
useEffect(() => {
const focusComposerOnType = (event: KeyboardEvent) => {
const composer = composerRef.current;

View file

@ -145,8 +145,6 @@ type SendMessageGet = (
data: { SendTime: number },
) => Promise<{ data: RawMessage }>;
type GetChatSecret = (userId: number) => Promise<Uint8Array | null>;
type StoredDraftState = ChatDraft & {
accountId: number;
userId: number;
@ -204,7 +202,7 @@ export async function fetchReplyMessage({
ownId: number;
chatUserId: number;
send: SendMessageGet;
getChatSecret: GetChatSecret;
getChatSecret: (userId: number) => Promise<Uint8Array | null>;
}) {
const message = await getMessage({
sendTime: replyTo,

View file

@ -21,12 +21,6 @@ import {
} from "./values";
import Wrapper from "@tensamin/user/wrapper";
type MessageChunk = {
key: string;
messages: Array<RawMessage | LiveMessage>;
startIndex: number;
};
function shouldFetchPreviousPage({
entry,
hasNextPage,
@ -108,7 +102,11 @@ function buildMessageChunks(
keyPrefix: string,
startOffset = 0,
) {
const chunks: MessageChunk[] = [];
const chunks: {
key: string;
messages: Array<RawMessage | LiveMessage>;
startIndex: number;
}[] = [];
for (let end = messages.length; end > 0; end -= MESSAGES_PER_VIRTUAL_ROW) {
const start = Math.max(0, end - MESSAGES_PER_VIRTUAL_ROW);
@ -282,7 +280,7 @@ export default function Screen() {
getItemKey,
estimateSize,
overscan: 2,
paddingStart: composerHeight + 8,
paddingStart: composerHeight + 20,
});
const totalSize = virtualizer.getTotalSize();
const contentHeight = Math.max(totalSize, viewportHeight);

View file

@ -1,7 +1,5 @@
import shortcodeData from "emojibase-data/en/shortcodes/joypixels.json";
type ShortcodeValue = string | string[];
export type EmojiDefinition = {
aliases: readonly string[];
hexcode: string;
@ -17,7 +15,7 @@ function normalizeName(value: string) {
}
export const emojis: readonly EmojiDefinition[] = Object.entries(
shortcodeData as Record<string, ShortcodeValue>,
shortcodeData as Record<string, string | string[]>,
).map(([hexcode, value]) => {
const aliases = Array.isArray(value) ? value : [value];
const name = aliases[0];

View file

@ -76,10 +76,6 @@ export type InputProps = {
onControllerChange?: (controller: InputController | null) => void;
};
type InputStyle = CSSProperties & {
"--tm-md-content-padding"?: string;
};
function toCssLength(value: CSSProperties["padding"]): string | undefined {
if (value === undefined) {
return undefined;
@ -99,11 +95,6 @@ function toCssPadding(
return `${toCssLength(vertical) ?? defaultVertical} ${toCssLength(horizontal) ?? defaultHorizontal}`;
}
type TokenRange = {
from: number;
to: number;
};
const hiddenTokenDecoration = Decoration.mark({ class: "tm-md-hidden-token" });
const strongDecoration = Decoration.mark({ class: "tm-md-strong" });
const emDecoration = Decoration.mark({ class: "tm-md-em" });
@ -443,7 +434,9 @@ export default function Input(props: InputProps) {
props.paddingX,
Boolean(props.styled),
),
} as InputStyle
} as CSSProperties & {
"--tm-md-content-padding"?: string;
}
}
/>
);
@ -834,7 +827,10 @@ function buildDecorations(view: EditorView): DecorationSet {
function addHiddenToken(
builder: Range<Decoration>[],
selections: ReadonlyArray<{ from: number; to: number }>,
token: TokenRange,
token: {
from: number;
to: number;
},
): void {
if (token.from >= token.to) return;

View file

@ -1,4 +1,11 @@
import { Fragment, type ReactElement, type ReactNode } from "react";
import {
Fragment,
useEffect,
useRef,
useState,
type ReactElement,
type ReactNode,
} from "react";
import Emoji from "./emoji";
import { findEmojiShortcodes } from "./emojiData";
@ -23,43 +30,11 @@ type InlineTokenRange = {
to: number;
};
type ParagraphBlock = {
type: "paragraph";
text: string;
};
type HeadingBlock = {
type: "heading";
level: number;
text: string;
};
type HrBlock = {
type: "hr";
};
type BlockQuoteBlock = {
type: "blockquote";
text: string;
};
type CodeBlock = {
type: "code";
language: string;
code: string;
};
type ListItem = {
text: string;
checked: boolean | null;
};
type ListBlock = {
type: "list";
ordered: boolean;
items: ListItem[];
};
type TableBlock = {
type: "table";
headers: string[];
@ -67,17 +42,140 @@ type TableBlock = {
};
type MarkdownBlock =
| ParagraphBlock
| HeadingBlock
| HrBlock
| BlockQuoteBlock
| CodeBlock
| ListBlock
| {
type: "paragraph";
text: string;
}
| {
type: "heading";
level: number;
text: string;
}
| {
type: "hr";
}
| {
type: "blockquote";
text: string;
}
| {
type: "code";
language: string;
code: string;
}
| {
type: "list";
ordered: boolean;
items: ListItem[];
}
| TableBlock;
const INLINE_TOKEN_REGEX =
/!\[([^\]]*)\]\(([^)\s]+(?:\s+"[^"]*")?)\)|\[([^\]]+)\]\(([^)\s]+(?:\s+"[^"]*")?)\)|`([^`\n]+)`|~~([^~\n]+)~~|\*\*([^*\n]+)\*\*|__([^_\n]+)__|\*([^*\n]+)\*|(?<![a-zA-Z0-9:])_([^_\n]+)_(?![a-zA-Z0-9:])/g;
function CopiedIndicator({
block,
visible,
}: {
block: boolean;
visible: boolean;
}) {
return (
<span
className={`pointer-events-none inline-flex align-middle text-foreground transition-opacity duration-200 ease-out ${block ? "mt-3 shrink-0" : "ml-1"} ${visible ? "opacity-100" : "opacity-0"}`}
aria-live="polite"
aria-hidden={!visible}
>
<svg
className="size-3.5"
viewBox="0 0 16 16"
fill="none"
aria-hidden="true"
>
<rect
x="3"
y="3.5"
width="10"
height="11"
rx="2"
stroke="currentColor"
strokeWidth="1.5"
/>
<path
d="M6 4V2.75C6 2.06 6.56 1.5 7.25 1.5h1.5c.69 0 1.25.56 1.25 1.25V4"
stroke="currentColor"
strokeWidth="1.5"
strokeLinecap="round"
strokeLinejoin="round"
/>
</svg>
<span className="sr-only">Copied</span>
</span>
);
}
function CopyableCode({
block = false,
language,
value,
}: {
block?: boolean;
language?: string;
value: string;
}) {
const [copied, setCopied] = useState(false);
const copiedTimer = useRef<ReturnType<typeof setTimeout> | undefined>(
undefined,
);
useEffect(
() => () => {
clearTimeout(copiedTimer.current);
},
[],
);
async function copy() {
await navigator.clipboard.writeText(value);
setCopied(true);
clearTimeout(copiedTimer.current);
copiedTimer.current = setTimeout(() => setCopied(false), 1200);
}
const code = (
<code
className={block ? "tm-md-codeblock" : "tm-md-code"}
data-language={language}
role="button"
tabIndex={0}
onClick={() => void copy()}
onKeyDown={(event) => {
if (event.key !== "Enter" && event.key !== " ") return;
event.preventDefault();
void copy();
}}
>
{value}
</code>
);
if (block) {
return (
<div className="flex min-w-0 items-start gap-1">
<pre className="tm-md-pre min-w-0 flex-1">{code}</pre>
<CopiedIndicator block visible={copied} />
</div>
);
}
return (
<>
{code}
<CopiedIndicator block={false} visible={copied} />
</>
);
}
/**
* Executes parseInlineNodes.
* @param input Parameter input.
@ -429,11 +527,7 @@ function renderInline(nodes: InlineNode[]): ReactNode[] {
}
if (node.type === "code") {
return (
<code key={index} className="tm-md-code">
{node.value}
</code>
);
return <CopyableCode key={index} value={node.value} />;
}
if (node.type === "link") {
@ -523,11 +617,12 @@ export function renderBlocks(blocks: MarkdownBlock[]): ReactElement {
if (block.type === "code") {
return (
<pre key={blockIndex} className="tm-md-pre">
<code className="tm-md-codeblock" data-language={block.language}>
{block.code}
</code>
</pre>
<CopyableCode
key={blockIndex}
block
language={block.language}
value={block.code}
/>
);
}
@ -666,7 +761,7 @@ function readTable(
}
const markdownStyles = `
.tm-md-root { color: hsl(var(--foreground)); line-height: 1.65; font-size: 1rem; }
.tm-md-root { color: var(--foreground); line-height: 1.65; font-size: 1rem; }
.tm-md-heading { margin: 0.2rem 0 0.35rem; font-weight: 700; line-height: 1.25; }
.tm-md-h1 { font-size: 1.65rem; }
.tm-md-h2 { font-size: 1.45rem; }
@ -676,13 +771,15 @@ const markdownStyles = `
.tm-md-h6 { font-size: 0.95rem; opacity: 0.9; }
.tm-md-blockquote { margin: 0.45rem 0; padding-left: 0.75rem; opacity: 0.95; }
.tm-md-blockquote p { margin: 0.2rem 0; }
.tm-md-pre { margin: 0.45rem 0; padding: 0.65rem 0.75rem; border-radius: 0.5rem; background: hsl(var(--muted)); overflow-x: auto; }
.tm-md-code, .tm-md-codeblock { font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace; }
.tm-md-code { padding: 0.08rem 0.32rem; border-radius: 0.28rem; background: hsl(var(--muted)); }
.tm-md-pre { margin: 0.45rem 0; padding: 0.65rem 0.75rem; border-radius: 0.5rem; background: var(--muted); overflow-x: auto; }
.tm-md-code, .tm-md-codeblock { font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace; font-size: 0.87em; cursor: pointer; }
.tm-md-code { padding: 0.08rem 0.32rem; border: 1px solid var(--border); border-radius: 0.28rem; background: var(--muted); }
.tm-md-codeblock { display: block; }
.tm-md-code:focus-visible, .tm-md-codeblock:focus-visible { outline: 2px solid var(--ring); outline-offset: 2px; }
.tm-md-strong { font-weight: 700; }
.tm-md-em { font-style: italic; }
.tm-md-del { text-decoration: line-through; }
.tm-md-link { color: hsl(var(--primary)); text-decoration: underline; text-underline-offset: 0.14rem; }
.tm-md-link { color: var(--primary); text-decoration: underline; text-underline-offset: 0.14rem; }
.tm-md-image { display: block; max-width: 100%; border-radius: 0.4rem; margin: 0.5rem 0; }
.tm-md-emoji { display: inline-block; width: 1.15em; height: 1.15em; vertical-align: -0.18em; }
.tm-md-ul, .tm-md-ol { margin: 0.3rem 0 0.35rem 1.2rem; padding: 0; }
@ -691,7 +788,7 @@ const markdownStyles = `
.tm-md-table-wrap { overflow-x: auto; margin: 0.45rem 0; }
.tm-md-table { border-collapse: collapse; width: 100%; min-width: 16rem; }
.tm-md-table th, .tm-md-table td { padding: 0.4rem 0.5rem; text-align: left; }
.tm-md-table th { background: hsl(var(--muted)); font-weight: 600; }
.tm-md-table th { background: var(--muted); font-weight: 600; }
.tm-md-hr { margin: 0.55rem 0; }
.cm-editor.tm-md-editor { border-radius: inherit; background: transparent; caret-color: var(--foreground); }
@ -699,10 +796,10 @@ const markdownStyles = `
.cm-editor.tm-md-editor .cm-scroller { font-family: inherit; line-height: 1.55; max-height: 30vh; overflow-y: auto; overflow-x: hidden; }
.cm-editor.tm-md-editor .cm-content { caret-color: var(--foreground); }
.cm-editor.tm-md-editor .cm-content { padding: var(--tm-md-content-padding, 0.25rem 0.625rem); min-height: 2rem; }
.cm-editor.tm-md-editor .cm-line { padding: 0; color: hsl(var(--foreground)); }
.cm-editor.tm-md-editor .cm-line { padding: 0; color: var(--foreground); }
.cm-editor.tm-md-editor .tm-md-editor-emoji { display: inline-block; width: 1.15em; height: 1.15em; vertical-align: -0.18em; object-fit: contain; pointer-events: none; }
.cm-editor.tm-md-editor .tm-md-hidden-token { color: transparent; opacity: 0; font-size: inherit; }
.cm-editor.tm-md-editor .tm-md-code-line { font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace; background: hsl(var(--muted)); border-radius: 0.3rem; }
.cm-editor.tm-md-editor .tm-md-code-line { font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace; background: var(--muted); border-radius: 0.3rem; }
.cm-tooltip.cm-tooltip-autocomplete { min-width: 18rem; max-width: min(26rem, calc(100vw - 1rem)); overflow: hidden; border: 1px solid var(--border); border-radius: var(--radius); background: var(--popover); color: var(--popover-foreground); box-shadow: 0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1); font-family: "Public Sans Variable", sans-serif; font-size: 0.875rem; }
.cm-editor.tm-md-editor .cm-tooltip.cm-tooltip-autocomplete > ul { max-height: min(20rem, 45vh); padding: 0.25rem; font-family: "Public Sans Variable", sans-serif; scrollbar-width: thin; scrollbar-color: var(--border) transparent; }
.cm-tooltip.cm-tooltip-autocomplete > ul::-webkit-scrollbar { width: 6px; height: 6px; }
@ -726,10 +823,15 @@ export function ensureMarkdownStyles(): void {
if (typeof document === "undefined") return;
const styleId = "tensamin-markdown-styles";
if (document.getElementById(styleId)) return;
let style = document.getElementById(styleId) as HTMLStyleElement | null;
const style = document.createElement("style");
style.id = styleId;
style.textContent = markdownStyles;
document.head.appendChild(style);
if (!style) {
style = document.createElement("style");
style.id = styleId;
document.head.appendChild(style);
}
if (style.textContent !== markdownStyles) {
style.textContent = markdownStyles;
}
}

View file

@ -631,16 +631,6 @@ type NativeSnapshot = {
error?: string;
};
type NativeEvent =
| { kind: "state"; snapshot: NativeSnapshot }
| { kind: "message"; generation: number; message: unknown }
| {
kind: "log";
level: number;
message: string;
details?: unknown;
};
function TauriProvider(props: {
children: ReactNode;
blockConnection?: boolean;
@ -713,7 +703,16 @@ function TauriProvider(props: {
let disposed = false;
let unlisten: UnlistenFn | undefined;
void (async () => {
unlisten = await listen<NativeEvent>("mtp://event", ({ payload }) => {
unlisten = await listen<
| { kind: "state"; snapshot: NativeSnapshot }
| { kind: "message"; generation: number; message: unknown }
| {
kind: "log";
level: number;
message: string;
details?: unknown;
}
>("mtp://event", ({ payload }) => {
if (disposed) return;
if (payload.kind === "state") {
applySnapshot(payload.snapshot);

View file

@ -5,7 +5,7 @@ import { useMTP } from "@tensamin/mtp";
import { createContext, useEffect, useContext } from "react";
import { toast as sonnerToast } from "sonner";
import { Avatar, AvatarFallback, AvatarImage } from "@methanium/ui";
import { isTauri } from "@tauri-apps/api/core";
import { invoke, isTauri } from "@tauri-apps/api/core";
import {
isPermissionGranted as isTauriNotificationPermissionGranted,
requestPermission as requestTauriNotificationPermission,
@ -108,7 +108,30 @@ export default function Provider(props: { children: React.ReactNode }) {
(await requestTauriNotificationPermission()) === "granted";
if (permissionGranted) {
sendTauriNotification({ title: user.Display, body: content });
let handledNatively = false;
try {
handledNatively = await invoke<boolean>(
"mtp_post_message_notification",
{
senderId: user.UserId,
sender: user.Display,
body: content,
avatar: user.Avatar,
},
);
} catch (error) {
log(
1,
"notifications",
"red",
"Failed to create native message notification",
error,
);
}
if (!handledNatively) {
sendTauriNotification({ title: user.Display, body: content });
}
}
} else {
const hasPermissions = await requestNotificationPermission();

View file

@ -21,10 +21,10 @@ export {
type OnboardingStepControls,
} from "@methanium/ui";
type LegalDocs = z.infer<typeof legalDocsSchema>;
interface GateState {
docs: LegalDocs;
docs: z.infer<typeof legalDocsSchema>;
acceptedPP: boolean;
acceptedTOS: boolean;
includeLegal: boolean;

View file

@ -5,7 +5,7 @@ import type { z } from "zod";
import { useOnboardingStep } from "@methanium/ui";
type LegalDocs = z.infer<typeof legalDocsSchema>;
export default function LegalPage({
docs,
@ -13,7 +13,7 @@ export default function LegalPage({
initiallyAcceptedTOS,
onAccept,
}: {
docs: LegalDocs;
docs: z.infer<typeof legalDocsSchema>;
initiallyAcceptedPP: boolean;
initiallyAcceptedTOS: boolean;
onAccept: () => Promise<void>;

View file

@ -5,9 +5,7 @@ import { storageDefaults, type Storage } from "@tensamin/shared/data";
import { settingsStorageDefaults } from "@tensamin/shared/settings";
import { useStorage } from "@tensamin/storage/context";
type BooleanStorageKey = {
[K in keyof Storage]: Storage[K] extends boolean ? K : never;
}[keyof Storage];
type ListStorageKey = {
[K in keyof Storage]: Storage[K] extends (string | number)[] ? K : never;
@ -21,7 +19,9 @@ export function Switch({
id,
}: {
label: React.ReactNode;
id: keyof typeof settingsStorageDefaults & BooleanStorageKey;
id: keyof typeof settingsStorageDefaults & ({
[K in keyof Storage]: Storage[K] extends boolean ? K : never;
}[keyof Storage]);
}) {
const { save, load } = useStorage();
const [value, setValue] = useState<boolean>(settingsStorageDefaults[id]);

View file

@ -143,25 +143,7 @@ export type Contacts = z.infer<typeof authPayload.shape.Contacts>;
export type Communities = z.infer<typeof authPayload.shape.Communities>;
export type Calls = z.infer<typeof authPayload.shape.Calls>;
type Base16Palette = Record<
| "base00"
| "base01"
| "base02"
| "base03"
| "base04"
| "base05"
| "base06"
| "base07"
| "base08"
| "base09"
| "base0A"
| "base0B"
| "base0C"
| "base0D"
| "base0E"
| "base0F",
string
>;
// MTP
const user = z.object({
@ -472,7 +454,25 @@ export interface Storage extends SettingsStorageDefaults {
call_mute_range_start: number;
call_mute_range_end: number;
theme_color: string;
theme_palette: Base16Palette | null;
theme_palette: Record<
| "base00"
| "base01"
| "base02"
| "base03"
| "base04"
| "base05"
| "base06"
| "base07"
| "base08"
| "base09"
| "base0A"
| "base0B"
| "base0C"
| "base0D"
| "base0E"
| "base0F",
string
> | null;
theme_primary_color: string;
theme_polarity: "dark" | "light" | "system";
theme_tint: "soft" | "hard" | "extreme";

View file

@ -22,7 +22,11 @@ export type DesktopScreenShareCapabilities = {
hasReliableSystemAudio: boolean;
};
type ElectronDesktopApi = {
declare global {
interface Window {
tensaminDesktop?: {
media?: {
getScreenShareCapabilities?: () => Promise<DesktopScreenShareCapabilities>;
listScreenShareSources?: () => Promise<DesktopScreenShareSource[]>;
@ -53,10 +57,6 @@ type ElectronDesktopApi = {
clear?: () => Promise<void>;
};
};
declare global {
interface Window {
tensaminDesktop?: ElectronDesktopApi;
}
}

View file

@ -1,14 +1,14 @@
type StringKeyOf<T> = Extract<keyof T, string>;
type SettingDefinition = {
display: string;
type: string;
default?: unknown;
};
export type SettingsSchema = Record<
string,
Record<string, Record<string, SettingDefinition>>
Record<string, Record<string, {
display: string;
type: string;
default?: unknown;
}>>
>;
const settings = {