// Development-only harness: renders the wayBetter panel in a plain browser (`vite dev`, then // open `/?panel`) with the native commands mocked in memory, for visual review at any width. // Not bundled into production (main.tsx imports it only when `import.meta.env.DEV`). import { StrictMode } from 'react'; import { createRoot } from 'react-dom/client'; import { nextDraft, nextStatus, toRevision } from '../../core/drafts'; import type { Draft, DraftRevision, SaveDraftInput } from '../../core/types'; import { storeHandlers } from '../../shell/preview/storeMocks'; import { settingsHandlers } from '../../shell/preview/settingsMocks'; import { X_FEATURES } from '../../areas/table'; type Handler = (args: Record) => unknown; const state = { theme: { preset: 'night-ink', accent: null } as unknown, scopes: { chrome: 'theme', profiles: {}, panes: {} } as unknown, features: {} as Record, settings: { homeUrl: 'https://x.com/home', externalLinks: 'pane', siteLinks: 'same', restoreTabs: true }, alerts: { enabled: true, keywords: ['tauri', 'waybetter', 'rust'] }, media: { folders: ['C:\\Users\\you\\Pictures\\Screenshots', 'C:\\Users\\you\\Desktop\\memes'], clipboardEnabled: true, clipboardMax: 30 }, css: '/* Hide the right sidebar on narrow windows */\n@media (max-width: 1100px) {\n [data-testid="sidebarColumn"] { display: none; }\n}\n', // `?onboarding=fresh|existing` shows the first-run screen (a new install, or a setup from before modes). mode: { mode: null as string | null, onboarded: true, existing: true } as { mode: string | null; onboarded: boolean; existing: boolean; preset?: Record | null }, plugins: [ // The bundled plugins that are not ported into their area yet: rows of the area cards. ...X_FEATURES.filter(feature => feature.backing === 'plugin').map(feature => ({ file: feature.file!, name: feature.file!.replace(/^bt-|\.plugin\.js$/g, ''), description: '', author: 'wayBetter', version: '1.2.0', enabled: feature.id === 'reader.cleanLinks' || feature.id === 'profile.userNotes', permissions: [...(feature.permissions ?? []), 'network:none'] as string[] | null, })), { file: 'hide-trends.plugin.js', name: 'Hide Trends', description: 'Removes the trends module everywhere.', author: 'waybetter', version: '1.2.0', enabled: true, permissions: ['network:none'] as string[] | null }, { file: 'focus-mode.plugin.js', name: 'Focus mode', description: 'Dims everything but the timeline after 10 pm.', author: '', version: '', enabled: false, permissions: null as string[] | null }, ], }; const params = new URLSearchParams(location.search); // Google Fonts in the harness: the browser fetches what native code would (same CSS2 API and // gstatic files), so the font browser and previews can be reviewed without the app. type Face = { weight: [number, number]; unicodeRange: string | null; data: string }; type Weights = { kind: 'range'; min: number; max: number } | { kind: 'list'; values: number[] }; const fonts = new Map(); const query = (weights: Weights) => weights.kind === 'range' ? `wght@${weights.min}..${weights.max}` : `wght@${weights.values.join(';')}`; async function googleFaces(family: string, weights: Weights, text?: string): Promise { const url = `https://fonts.googleapis.com/css2?family=${encodeURIComponent(family).replace(/%20/g, '+')}:${query(weights)}${text ? `&text=${encodeURIComponent(text)}` : ''}`; const css = await (await fetch(url)).text(); const blocks = [...css.matchAll(/(?:\/\*\s*([\w-]+)\s*\*\/\s*)?@font-face\s*{([^}]*)}/g)]; const keep = blocks.some(block => block[1]) ? blocks.filter(block => block[1] === 'latin' || block[1] === 'latin-ext') : blocks; return Promise.all(keep.map(async block => { const body = block[2]!; const src = /url\(([^)]+)\)/.exec(body)![1]!; const [min, max = min] = /font-weight:\s*([\d ]+);/.exec(body)![1]!.trim().split(/\s+/).map(Number) as [number, number?]; const bytes = new Uint8Array(await (await fetch(src)).arrayBuffer()); let binary = ''; for (const byte of bytes) binary += String.fromCharCode(byte); return { weight: [min, max] as [number, number], unicodeRange: /unicode-range:\s*([^;]+);/.exec(body)?.[1] ?? null, data: btoa(binary) }; })); } if (params.has('empty')) { state.plugins = []; state.media.folders = []; state.alerts.keywords = []; } // `?mode=advanced` (with `&preset=a,b`: the flags that mode had turned on when it was applied) is the stored choice. if (params.get('mode')) state.mode = { ...state.mode, mode: params.get('mode'), preset: params.has('preset') ? Object.fromEntries(params.get('preset')!.split(',').filter(Boolean).map(flag => [flag, true])) : null }; if (params.get('onboarding')) state.mode = { mode: null, onboarded: false, existing: params.get('onboarding') === 'existing' }; // `?flags=hideSidebar,navigation.focusMode` turns flags on; `?off=area.chat` turns flags off. for (const flag of (params.get('flags') ?? '').split(',').filter(Boolean)) state.features[flag] = true; for (const flag of (params.get('off') ?? '').split(',').filter(Boolean)) state.features[flag] = false; if (params.get('theme')) state.theme = { preset: params.get('theme'), accent: null }; const handlers: Record = { x_theme_get: () => state.theme, x_set_theme: ({ theme }) => { state.theme = theme; }, theme_scopes_get: () => state.scopes, theme_scopes_set: ({ scopes }) => { state.scopes = scopes; }, x_preview_theme: () => null, gfonts_installed: () => [...fonts.values()].map(({ faces, ...font }) => ({ ...font, faces: faces.length })), gfonts_install: async ({ family, weights }) => { const faces = await googleFaces(String(family), weights as Weights); const font = { family: String(family), weights: weights as Weights, faces, bytes: faces.reduce((sum, face) => sum + face.data.length * 0.75, 0), installedAt: new Date().toISOString() }; fonts.set(font.family, font); return { ...font, faces: faces.length }; }, gfonts_remove: ({ family }) => { fonts.delete(String(family)); }, gfonts_faces: ({ family }) => { const font = fonts.get(String(family)); if (!font) throw new Error('FONTS: not installed'); return { family, faces: font.faces }; }, gfonts_preview: ({ family, weights, text }) => googleFaces(String(family), weights as Weights, String(text)), open_external_url: () => null, alerts_get: () => state.alerts, alerts_set: ({ settings }) => (state.alerts = settings as typeof state.alerts), media_get: () => state.media, media_set: ({ settings }) => (state.media = settings as typeof state.media), gallery_add_folder: () => (state.media = { ...state.media, folders: [...state.media.folders, `C:\\Users\\you\\Pictures\\Folder ${state.media.folders.length + 1}`] }), clip_remove: () => null, 'plugin:event|listen': () => 1, 'plugin:event|unlisten': () => null, }; // The draft vault, in memory (native code keeps it in SQLite with the same revision rules, core/drafts.ts). const vault = { drafts: new Map(), revisions: [] as DraftRevision[] }; Object.assign(handlers, { draft_list: () => [...vault.drafts.values()].sort((a, b) => b.updatedAt.localeCompare(a.updatedAt)), draft_save: ({ input }) => { const { draft, revision } = nextDraft(vault.drafts.get((input as SaveDraftInput).id), input as SaveDraftInput, new Date().toISOString()); vault.drafts.set(draft.id, draft); vault.revisions.push(revision); return draft; }, draft_revisions: ({ draftId }) => vault.revisions.filter(revision => revision.draftId === draftId).sort((a, b) => b.revision - a.revision), draft_status: ({ id, expectedRevision, status }) => { const draft = nextStatus(vault.drafts.get(String(id)), Number(expectedRevision), status as Draft['status'], new Date().toISOString()); vault.drafts.set(draft.id, draft); vault.revisions.push(toRevision(draft)); return draft; }, data_export: () => ({ version: 1, exportedAt: new Date().toISOString(), drafts: [...vault.drafts.values()], revisions: vault.revisions, observations: [] }), } satisfies Record); // The Store section and the install screen (`?section=store`, `&offline` for an unreachable store). const pluginBox = { list: state.plugins }; Object.assign(handlers, storeHandlers(pluginBox, { offline: params.has('offline') })); // Backup & sync and Developer sections (`?section=backup&sync=on|newer|locked|folder`, `?section=developer&dev=errors`). Object.assign(handlers, settingsHandlers()); let callbackId = 0; (window as unknown as { __TAURI_INTERNALS__: unknown }).__TAURI_INTERNALS__ = { invoke: async (cmd: string, args: Record = {}) => { const handler = handlers[cmd]; if (!handler) throw new Error(`Preview: ${cmd} is not mocked`); return structuredClone(await handler(args)); }, transformCallback: () => ++callbackId, unregisterCallback: () => {}, metadata: { currentWindow: { label: 'shell' }, currentWebview: { label: 'shell' } }, }; (window as unknown as { __TAURI_EVENT_PLUGIN_INTERNALS__: unknown }).__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} }; // Plugins, custom CSS, tweaks and the browser settings (waybetter-host commands). Object.assign(handlers, { features_get: () => state.features, features_set: ({ features }) => { state.features = features as Record; }, mode_get: () => state.mode, mode_set: ({ mode, onboarded, preset }) => (state.mode = { ...state.mode, mode: (mode as string | null) ?? null, onboarded: !!onboarded, preset: (preset as Record | undefined) ?? (mode === state.mode.mode ? state.mode.preset : null) }), settings_get: () => state.settings, settings_set: ({ settings }) => (state.settings = settings as typeof state.settings), custom_css_get: () => state.css, custom_css_set: ({ css }) => { state.css = String(css); }, plugins_list: () => pluginBox.list, plugin_set_enabled: ({ file, enabled }) => (pluginBox.list = pluginBox.list.map(p => p.file === file ? { ...p, enabled: !!enabled } : p)), plugins_open_folder: () => null, } satisfies Record); export async function mountPanelHarness(root: HTMLElement) { // X's site sets the shell frame up (the panel uses its accounts, decks, themes and stores). await import('../../shell/site'); const [{ Panel }, { InstallHost }] = await Promise.all([import('../Panel'), import('../../shell/InstallDialog')]); document.body.style.margin = '0'; document.body.style.background = '#07080c'; root.style.cssText = 'position:fixed;inset:0'; const section = params.get('section'); createRoot(root).render(); }