Моды TeleX
Мод — один файл .module. Внутри может быть что угодно: тема, HTML-виджет, JS, CSS. Любой экран приложения можно изменить или дополнить.
Мод — расширение, которое работает внутри приложения с полным доступом к его API (песочницы нет сознательно). Поэтому установщик показывает предупреждение, а поле manifest.verified зарезервировано под будущую проверку модов. Моды ставятся в Настройки → Моды (или из «Настроек чатов» → «Моды тем»): из файла .module, по ссылке https://… или вставкой текста.
Файл .module
Мод — файл с расширением .module. Это обычный текст, внутри может быть что угодно: HTML, JS, CSS, тема, JSON-данные. Поддерживаются две формы.
1. JSON-пакет — несколько частей в одном файле:
{
"manifest": { "id": "my-mod", "name": "Мой мод", "version": "1.0.0", "author": "me",
"description": "коротко", "about": "подробно\nв несколько строк",
"icon": "clock", "preview": ["https://…/1.png", "data:image/png;base64,…"], "tags": ["theme"],
"settings": [ { "key": "seconds", "type": "switch", "title": "Секунды", "default": false } ] },
"parts": [
{ "type": "theme", "data": { … } },
{ "type": "css", "code": "…" },
{ "type": "html", "code": "<div>…</div><script>…</script>" },
{ "type": "js", "code": "export default function (tx) { … }" },
{ "type": "json", "name": "table", "data": { … } }
]
}
2. Один исходник с аннотацией — первая строка-комментарий с @manifest {json}, остальное — тело. Тело, начинающееся с <, — HTML (скрипты внутри выполняются), JSON с ключами темы — тема, иначе — JS-модуль. Примеры: // @manifest {…}, <!-- @manifest {…} -->.
3. Один большой файл с секциями — после строки @manifest каждая часть начинается строкой-комментарием @part js|css|html|theme|json|text [имя] (// @part css, /* @part js */, <!-- @part html -->). Так в одном файле умещаются стили, разметка и код.
id — латиница/цифры/._-, 2–41 символ. Размер — до 1,5 МБ. Мод только из theme/css не исполняет код, поэтому ставится без предупреждения о полном доступе.
Языки
Любой текст манифеста — name, description, about, title/sub/подписи options в настройках — можно задать либо строкой, либо по языкам: { "ru": "…", "en": "…", "es": "…", "pt": "…", "uk": "…" }. Берётся язык приложения, иначе английский. В коде: tx.L({ ru: '…', en: '…' }). Официальные моды переведены на все 5 языков.
Иконка
icon — эмодзи или картинка: data:image/svg+xml;base64,…, https://… либо путь внутри приложения (mods/icons/<id>.svg у официальных). Лучше SVG 96×96 со скруглённым квадратом и градиентом — как у официальных модов (app/static/mods/icons/).
Карточка и страница мода
description — короткое описание на карточке, about — подробное (на странице мода), preview — картинка или список картинок (https:// или data:image/…; без них рисуется превью темы или icon на градиенте), tags, author, version.
Настройки мода
manifest.settings — схема: { key, type: "switch" | "text" | "number" | "select" | "color", title, sub?, default, min?, max?, options? }. Страница мода рисует для них элементы сама. В коде: tx.config.get(key), tx.config.set(key, v), tx.config.on(key | '*', fn); для собственного блока на странице — tx.config.render((box) => { … }). В HTML-частях объект доступен как TeleXMods['<id>'].
Тема (theme-часть)
| поле | что делает |
|---|---|
vars | CSS-переменные: { "all": {}, "dark": {}, "light": {} }, например --tx-bg, --tx-accent, --tx-bubble-out, --tx-surface, --tx-text (список — app/static/css/tx/tokens.css) |
css | произвольный CSS |
wallpapers[] | обои в выбор: { id, name, kind: "fill" | "pattern", colors: ["#rrggbb"…], rotation, intensity, url? } (как у обоев Telegram: 1–4 цвета; intensity < 0 — тёмный фон; url паттерна — svg) |
colorThemes[] | цветовая тема в карусели «Настроек чатов»: { id, emoji, accent?, out: { dark: [цвета], light: [цвета] }, wallpapers: { dark, light } } — у темы свои обои для дня и ночи |
apply | id цветовой темы, которую выбрать сразу после установки |
API кода (tx)
export default function (tx) { … } (в HTML-частях — TeleXMods['<id>']).
| что | зачем |
|---|---|
tx.theme | setVars(vars, mode), addCss(css), addColorTheme(theme), addWallpaper(wp), setWallpaper(id), select(themeId), mode() |
tx.ui | watch(selector, fn) — fn(el) для существующих и будущих элементов; inject(selector, html, where) — вставить разметку в любой экран; root() |
tx.ext | addMenu(point, provider), addHook(name, fn), on(event, fn) — см. «Точки расширения» |
tx.settings | addRow({ title, sub, icon, color, run }), addPage({ id, title, sub, icon, render(box) }) — свой экран в настройках |
tx.config | настройки мода: get, set, on(key | '*', fn), render(fn(box)) |
tx.storage | get(k), set(k, v) — произвольные данные мода |
tx.onStop(fn) | своя очистка (таймеры, узлы) при выключении мода |
tx.data | части json/text из пакета, по name |
tx.S, tx.api | состояние приложения (S.posts, S.channels, S.user) и весь доступ к Telegram |
tx.t, tx.toast, tx.confirm, tx.escapeHtml | перевод, всплывашка, диалог, экранирование |
Точки расширения (tx.ext)
- меню
post— пункты меню поста: провайдер получает{ post }и возвращает[{ label, icon, run }]; - меню
settings— строки на экране настроек; - хук
postText(синхронный) — готовый HTML текста поста → HTML; - события
view(сменился экран).
Так как это веб-приложение, мод может и напрямую менять DOM любого экрана (tx.ui.watch) — это и есть «внедрить что угодно». Всё, что мод добавил (стили, переменные, темы, обои, меню, наблюдатели, HTML, вставки), снимается при выключении или удалении.
Скин: переделать весь интерфейс одними переменными
Слой css/tx/skin.css выключен, пока на <html> нет класса tx-skin. Мод включает его вызовом tx.theme.setSkin(tokens, mode) (или частью темы skin), и все основные поверхности приложения начинают рисоваться из токенов --sk-* — в дневном и ночном режиме. Знать имена классов не нужно.
| токен | что красит |
|---|---|
--sk-card-bg -border -shadow -filter -radius | карточки: группы настроек, пузыри постов и сообщений |
--sk-bubble-in --sk-bubble-out --sk-bubble-radius | входящие / исходящие пузыри |
--sk-bar-bg -border -shadow -filter -radius | нижняя панель, поиск, вкладки, «пилюли» шапки, поле ввода |
--sk-menu-bg -border -shadow -filter -radius | контекстные меню, полоса реакций |
--sk-dialog-bg --sk-dialog-radius | диалоги |
--sk-button-bg --sk-button-text --sk-button-radius | кнопки |
--sk-chip-bg --sk-chip-radius | реакции, плашка активной вкладки, теги |
--sk-highlight | светлая кромка сверху у всех поверхностей (внутренняя тень) |
--sk-overlay, --sk-separator, --sk-field-bg | затемнение под меню/диалогами, разделители, поля ввода |
Акцентный цвет всего приложения — tx.theme.setAccent('#0a84ff', '#007aff') (второй — для дня) или поле accent/accentDay в части темы. Базовые токены цвета (--tx-bg, --tx-surface, --tx-text, --tx-accent* …) — в css/tx/tokens.css.
Поверхности, которые можно менять напрямую
Если токенов мало — стилизуйте классы (мод-CSS подключается последним и перебивает стили приложения при равной специфичности): .tx-dock (нижняя панель), .tx-glass (пилюли шапки), .tx-search-main, .tx-tabs, .tx-bubble / .tx-bubble.is-out (пост, сообщение), .tx-group / .tx-row (настройки), .tx-menu, .tx-ctx-reactions, .tx-dialog, .tx-btn, .tx-reaction, .tx-mainbar (верхняя панель ленты), .tx-titlebar, .tx-mod-card. Экраны: #screen-wall, #screen-settings, #screen-profile, #screen-thread, #screen-channel.
Куда что вставлять (слоты)
tx.ui.add(слот, { id, title?, icon?, run?, html?, el?, render?(host, ctx), position? }) — вставка в именованное место интерфейса; снимается при выключении мода.
| слот | где | что вставлять |
|---|---|---|
dock | нижняя панель | кнопка-вкладка |
topbar | верхняя панель ленты (рядом с «TeleX» и меню) | кнопка или виджет |
search | внутри поля поиска | кнопка (фильтр, голос…) |
tabs | вкладки ленты (Все · Медиа · …) | ещё одна вкладка |
fab | плавающая круглая кнопка | кнопка |
post.header | рядом с названием канала в посте | значок, бейдж |
post.footer | под текстом поста | блок (статистика, перевод, заметка) |
post.actions | рядом с кнопкой «поделиться» | кнопка |
Остальное: пункт в меню поста — tx.ext.addMenu('post', …); строка/страница в настройках — tx.settings.addRow/addPage; свой экран — tx.ui.openScreen; текст постов — хук postText; реакция на каждый пост — tx.ui.onPost; внешний вид — tx.theme.*. Пример со всеми слотами: mods-examples/slots-demo.module.
Виды модов
Тема (без кода) · виджет (часы, погода, счётчик) · кнопка-инструмент · улучшение постов · фильтр (скрыть по словам/каналам) · своя страница (статистика, блокнот).
Новые экраны и кнопки
tx.ui.openScreen({ title, render(box, { close }) })— свой полноэкранный экран; жест «назад» закрывает его.tx.ui.addDockItem({ id, title, icon, run })— кнопка в нижней панели (icon— эмодзи, SVG-разметка или имя иконки).tx.settings.addPage(...)— свой экран внутри настроек.tx.ui.onPost((el, post) => …)— для каждой карточки поста, сейчас и при появлении новых; событиеpostдляtx.ext.on.tx.app—openChannel(id),openThread(postId),setView('wall'|'settings'|'profile'),openSettings(page),reloadFeed(),lang(),theme().
Жизненный цикл
Мод запускается при старте приложения, если включён. Всё, что он зарегистрировал через tx, снимается при выключении/удалении; свои таймеры и слушатели снимайте в tx.onStop. Официальные моды из каталога обновляются сами при выходе новой версии (настройки мода сохраняются). Обновление чужого мода — переустановка файла с тем же id.
Мод с помощью нейросети
В Настройки → Моды внизу: «Скопировать промпт для нейросети» → вставьте его в нейросеть и допишите, какой мод нужен → скопируйте ответ → «Вставить мод из буфера». Промпт содержит всю спецификацию и жёсткие правила вывода (только файл, без пояснений).
Публикация для всех (сообщество)
Положите <id>.module в community/mods/ через Pull Request — после проверки CI мод появится в приложении у всех (Настройки → Моды → Сообщество). Правила — в community/README.md.
Свой мод в каталоге
1. Положите файл <id>.module в app/static/mods/ и SVG-иконку в app/static/mods/icons/<id>.svg. 2. Добавьте запись в app/static/mods/catalog.json: { id, file, name, version, author, icon, description, tags } (name/description — по языкам). 3. Поднимите version, когда меняете мод — у пользователей он обновится сам. Мод из каталога получает значок проверенного.
Советы
- Делайте мод работающим в обеих темах: используйте токены, а не жёсткие цвета; проверяйте в
?дневном и ночном режимах. - Все тексты — на 5 языков (
{ru,en,es,pt,uk}), иконка — SVG 96×96. - Не полагайтесь на то, что узел DOM живёт долго: интерфейс перерисовывается — используйте
tx.ui.watch/tx.ui.onPost. - Не делайте тяжёлых вычислений при каждой прокрутке: экраны телефонов слабее, чем ваш компьютер.
Примеры — mods-examples/. Для нейросетей — docs/mods-for-agents.md.
ИИ в модах (tx.ai)
В TeleX есть встроенный ИИ. Мод может пользоваться им без собственного ключа: в манифесте указывается "permissions": ["ai"], а в коде вызывается tx.ai. Пользователь один раз вставляет бесплатный ключ Groq (Настройки → Ключ Groq), а при установке мода видит, что мод использует ИИ.
| Вызов | Что делает |
|---|---|
tx.ai.available() | true, если в манифесте есть право ai и ключ сохранён |
await tx.ai.ask('запрос', { system, json, maxTokens, temperature }) | один вопрос → строка |
await tx.ai.chat([{ role: 'user', content: '…' }, …], opts) | диалог → строка (объект при json: true) |
tx.lang() | язык приложения: ru, en, es, pt, uk |
Лимиты: не больше 12 запросов в минуту на мод, до 12 000 символов в сообщении, до 2 000 токенов ответа, последние 24 сообщения. Модель маленькая и быстрая — просите короткие ответы и не отправляйте секреты. Ошибки приходят исключением (e.message читаем для человека, e.code — no-key, limit или key): ловите их через .catch и показывайте сообщение. Мод может подключить и свой ИИ-сервис с собственным ключом (поле settings типа text), но лучше использовать tx.ai.
Готовые примеры — официальные моды «ИИ-чат» и «Переводчик постов» (app/static/mods/ai-chat.module, ai-translate.module).
Проверка модов ИИ перед установкой
Если добавлен ключ Groq, при установке мод проверяется ИИ: он ищет опасный код (отправка данных наружу, eval, чтение сессии) и то, что ломает интерфейс (элементы поверх статус-бара, скрытие панелей, глобальные селекторы). Результат — «проблем не найдено», «есть замечания» или «опасный код» — виден в окне установки. Это подсказка, а не гарантия: ставьте только моды, которым доверяете. Проверку можно отключить в Настройки → Ключ Groq.
Новые возможности API
| Что нужно | Как |
|---|---|
| пост уже отрисован (замерить высоту, свернуть) | tx.ui.onPostRendered((el, post, { height }) => …) — приходит через два кадра после появления карточки |
| текст поста | tx.ui.onPostText((textEl, post, card) => …) или слот post.text (position: 'start' — перед текстом) |
| смена темы | tx.theme.on('change', (palette) => …), tx.theme.palette() — актуальные цвета (для канваса) |
| пункт меню поста с галочкой и подменю | tx.ext.addMenu('post', ({ post }) => [{ label, icon, run, checked, items }]) |
| тост с кнопкой «Отмена» | tx.toast('Скрыто', { action: 'Отмена', run: () => … }) |
| горячие клавиши | tx.keys.add('mod+shift+c', fn) — снимаются вместе с модом, не срабатывают при вводе текста |
| погода / частицы / фоновая анимация | tx.ambient.add({ id, draw(ctx, w, h, dtMs, palette) }) — один общий холст и один цикл (≤ 30 кадров/с) на все моды. Свой полноэкранный canvas и свой requestAnimationFrame создавать не нужно |
| медиа поста | tx.media.of(post) → [{ type, url, thumb, duration, size }], tx.media.urls(post) |
| список каналов в настройках мода | поле { "type": "channels" } (массив id) или { "type": "select", "optionsFrom": "channels" } (один id) |
| конфликты | "conflicts": ["id-другого-мода"] в манифесте — при установке показывается предупреждение |
| наборы модов | presets в mods/catalog.json — одна кнопка ставит сразу несколько официальных модов («Зимний набор», «ИИ», «Читатель») |
Примеры: официальные моды «Снегопад» (tx.ambient), «Читать позже» (меню с галочкой, тост с «Отмена», страница в настройках), «Свернуть длинные посты» (onPostText).
Каталог модов (публикация без GitHub)
Во вкладке «Создать» у каждого вашего мода есть кнопка «Опубликовать»: мод попадает в общий каталог, его видят все пользователи, могут искать, ставить лайки, оценивать звёздами и устанавливать одним нажатием. Обновление — та же кнопка («Обновить»). Автор определяется секретом, который хранится на вашем устройстве, поэтому чужой мод перезаписать нельзя; убрать мод из каталога можно на его странице.
Сервер (server/) сразу отклоняет файлы, которые читают сессию Telegram или секреты приложения, отмечает eval, удалённые скрипты и сетевые запросы наружу, а после трёх жалоб скрывает мод. Моды из каталога никогда не получают метку «проверен» — её дают только официальным модам проекта. Разворачивание сервера: server/README.md.
Для нейросетей (инструкция агенту)
> NO EMOJI. Ever. Not in names, descriptions, buttons, toasts, dialogs, empty states, icon fields or code comments shown to the user. TeleX looks like Telegram: use the app's icon font (<i class="icon icon-send"></i>, names such as ai, language, copy, favorite, favorite-filled, warning, tools, key-filled, more, close, settings, article, stars-filled, darkmode, brush, info-filled, check-bold) or inline SVG with currentColor. The manifest icon is an icon-font name (e.g. "icon": "ai"), a 96×96 SVG (data:image/svg+xml;base64,…) or an https image — never an emoji.
Goal: you are asked to "make a mod/theme/widget for TeleX". Produce one file with the extension .module that the user installs in *Settings → Mods* (file, link or pasted text). No build step, no dependencies, no sandbox: the file runs inside the web app with full access.
Where to put what (pick the slot, do not guess selectors)
| The user wants… | Use |
|---|---|
| a button in the bottom bar (the dock) | tx.ui.add('dock', { id, icon, title, run }) |
| a button in the top bar of the feed (next to the TeleX title / menu) | tx.ui.add('topbar', { id, icon, title, run }) |
| something inside the search field (filter, voice…) | tx.ui.add('search', { id, icon, run }) |
| an extra feed tab (All · Media · Popular · Favorites · Yours) | tx.ui.add('tabs', { id, title, run }) |
| a round floating button | tx.ui.add('fab', { id, icon, run }) |
| a badge by the channel name on every post | tx.ui.add('post.header', { id, html }) |
| a block under the post text (stats, translate, notes) | tx.ui.add('post.footer', { id, render(el, { post }) {…} }) |
a block right before/after the post text (position: 'start' = before) | tx.ui.add('post.text', { id, render(el, { post }) {…} }) |
| a button beside the share button of a post | tx.ui.add('post.actions', { id, icon, run({ post }) {…} }) |
| an item in the post's context menu | tx.ext.addMenu('post', ({ post }) => [{ label, icon, run, checked?: bool | ({post}) => bool, items?: [submenu…] }]) — checked shows a tick, items opens a submenu with a Back row |
| a row or a whole page in Settings | tx.settings.addRow(...) / tx.settings.addPage(...) |
| a full screen of its own (opened from any button) | tx.ui.openScreen({ title, render(box) }) |
| to change text of posts | tx.ext.addHook('postText', (html) => html) |
| to react to every post (hide, mark, count) | tx.ui.onPost((el, post) => …) |
| to change the whole look | tx.theme.setSkin(...), tx.theme.setAccent(...), tx.theme.addCss(...) |
| a floating widget on top of the app | an html part (position: fixed) |
ui.add spec: { id, title?, icon?, run?, html?, el?, render?(host, ctx), position?: 'start'|'end' }. icon is an icon-font name (preferred) or an SVG string — never an emoji. Buttons are built from icon/title/run; html/render give you the whole element. Every slot is removed automatically when the mod is turned off.
AI inside a mod (tx.ai, free, uses the user's own Groq key)
TeleX has a built-in AI. A mod can use it without its own API key: declare "permissions": ["ai"] in the manifest and call tx.ai. The user adds a free Groq key once (Settings → Groq key); the install dialog tells them that the mod uses AI.
tx.ai.available()→truewhen the manifest has the permission and a key is saved. Check it before calling and show a hint (Settings → Groq key) otherwise.await tx.ai.stream(messages, { system?, maxTokens?, temperature?, signal? }, (textSoFar) => …)→ full text — the answer appears as it is written (use it in chats/translators, with anAbortControllerfor Stop).await tx.ai.ask('prompt', { system?, json?, maxTokens?, temperature? })→ stringawait tx.ai.chat([{ role: 'user'|'assistant', content }], { system?, json?, maxTokens?, temperature? })→ string (an object whenjson: true)tx.lang()→'ru'|'en'|'es'|'pt'|'uk'— tell the model which language to answer in.- Limits: ≤ 12 requests per minute per mod, ≤ 12 000 characters per message, ≤ 2 000 output tokens, last 24 messages. The model is small and fast (a Groq free-plan model): give short, concrete instructions, ask for a short answer, never send secrets.
- Errors are thrown (
e.messageis user-readable;e.codeis'no-key' | 'limit' | 'key') — always.catchand show the message. - A mod may also call any other AI with its own key: add a
settingsfield{ "key": "apiKey", "type": "text" }andfetchit yourself — but prefertx.ai.
Kinds that fit: a chat screen (ui.addDockItem + ui.openScreen), a "translate / summarise / explain" button on a post (post.actions → ask(post.text)), a post classifier or tone filter (ui.onPost + json: true, remember results in tx.storage, never one request per scrolled post), a writing helper. Full examples: app/static/mods/ai-chat.module, ai-translate.module.
// @manifest {"id":"ai-explain","name":"Explain","version":"1.0.0","icon":"lamp","description":"Explains a post in simple words","permissions":["ai"]}
// @part js
export default function (tx) {
tx.ui.add('post.actions', { id: 'explain', icon: 'lamp', title: 'Explain', run: function (ctx) {
if (!tx.ai.available()) { tx.toast('Settings → Groq key'); return; }
tx.ai.ask(String(ctx.post && ctx.post.text || '').slice(0, 4000), { system: 'Explain the text in two simple sentences.', maxTokens: 300 })
.then(function (a) { tx.ui.openScreen({ title: 'Explain', render: function (b) { b.textContent = a; } }); })
.catch(function (e) { tx.toast(e.message); });
} });
}
Kinds of mods (pick one, mix if needed)
1. Theme — theme part: colours, wallpapers, skin tokens. No code. 2. Widget — a small live element (clock, weather, counter): ui.add('topbar', { html }) or an html part, refresh with setInterval, clear it in tx.onStop. 3. Tool button — an icon that does one thing (dock/topbar/fab) and shows the result with tx.toast or tx.ui.openScreen. 4. Post enhancer — post.header/post.footer/post.actions, or ui.onPost + postText (translate, reading time, link previews, notes). 5. Filter — ui.onPost((el, post) => { if (…) el.style.display = 'none'; }) with settings for the words/channels to hide. 6. AI tool — permissions: ["ai"] + tx.ai.ask/chat (chat, translator, summariser, classifier). 7. Own page — ui.openScreen or settings.addPage (statistics, lists, a notebook stored in tx.storage).
Output contract
1. Write exactly one file, <id>.module, UTF-8 text. Do not wrap it in markdown fences when saving it to a file. 2. It must contain a manifest and one or more parts. Two accepted shapes:
A. JSON bundle (use this for anything with more than one part):
{
"manifest": {
"id": "my-mod", // required: [a-z0-9][a-z0-9._-]{1,40}
"name": "My mod", // required
"version": "1.0.0", "author": "me",
"description": "one line shown on the card",
"about": "longer text\nshown on the mod page",
"icon": "tools", // icon-font name (or an SVG data URL / https image); NEVER an emoji
"preview": ["https://…/shot.png"], // optional; https:// or data:image/…; a theme gets an auto preview
"tags": ["theme"],
"permissions": [], // [] | ["ai"] — "ai" unlocks tx.ai (the user's Groq key)
"settings": [ { "key": "size", "type": "number", "title": "Size", "default": 16, "min": 10, "max": 30 } ]
},
"parts": [
{ "type": "theme", "data": { } },
{ "type": "css", "code": "…" },
{ "type": "html", "code": "<div>…</div><script>const tx = TeleXMods['my-mod']; …</script>" },
{ "type": "js", "code": "export default function (tx) { … }" },
{ "type": "json", "name": "table", "data": { } }
]
}
B. Single annotated source — first line is a comment holding @manifest {one-line json}, the rest is the body: // @manifest {…} + JS module · <!-- @manifest {…} --> + HTML · /* @manifest {…} */ + JSON theme. Body starting with < = HTML, JSON with vars|colorThemes|wallpapers|css = theme, anything else = JS module (must export default function (tx)).
C. One big file with sections (best for an AI: one paste, many parts). After the @manifest line, start every part with a comment line @part js|css|html|theme|json|text [name] — e.g. // @part css, /* @part js */, <!-- @part html -->, // @part theme (JSON), // @part json table:
// @manifest {"id":"my-mod","name":{"ru":"…","en":"…"},"version":"1.0.0","description":{…}}
// @part css
.tx-dock { border-radius: 14px; }
// @part js
export default function (tx) { /* … */ }
Limits: total ≤ 1.5 MB. A mod made only of theme/css parts executes no code (the user gets a lighter confirmation).
Languages and icon (do this for every mod you publish)
Any manifest text (name, description, about, settings title/sub, options labels) may be a string or { "ru": "…", "en": "…", "es": "…", "pt": "…", "uk": "…" }. Provide all five when the mod is meant for others; the app picks its language, then English. In code use tx.L({ ru: '…', en: '…', … }). icon: an icon-font name, or an image — data:image/svg+xml;base64,… / https://… / mods/icons/<id>.svg (official mods). Prefer a 96×96 SVG: rounded square rx=22 with a two-colour gradient and a white stroke glyph (see app/static/mods/icons/*.svg).
Restyling the whole app (skin tokens)
tx.theme.setSkin({ '--sk-card-bg': '…', … }, 'all'|'dark'|'light') (or a theme part "skin": { "dark": {…}, "light": {…} }) turns on the skin layer (app/static/css/tx/skin.css): every main surface is then drawn from tokens — --sk-card-{bg,border,shadow,filter,radius}, --sk-bubble-{in,out,radius}, --sk-bar-{bg,border,shadow,filter,radius} (dock, pills, tabs, search), --sk-menu-{bg,border,shadow,filter,radius}, --sk-dialog-{bg,radius}, --sk-button-{bg,text,radius}, --sk-chip-{bg,radius}, --sk-highlight, --sk-overlay, --sk-separator, --sk-field-bg. Set both day and night. Accent of the whole app: tx.theme.setAccent(hex, dayHex?). For anything the tokens do not reach, add CSS (tx.theme.addCss) using the classes listed in docs/mods.md. New UI: tx.ui.openScreen({ title, render(box) }), tx.ui.addDockItem({ id, title, icon, run }), tx.settings.addPage, tx.ui.onPost((el, post) => …), tx.app.* (navigation). Official catalog: app/static/mods/catalog.json + <id>.module + icons/<id>.svg; bump version and installed copies update themselves.
Settings schema (manifest.settings[])
{ key, type, title, sub?, default, … } with type: switch (bool) · number (min,max,step) · select (options: ["a","b"] or [["value","Label"]]) · color (#rrggbb) · text. The mod page renders the controls. Read with tx.config.get(key); react with tx.config.on(key | '*', fn); for a custom block use tx.config.render((box) => { box.innerHTML = '…' }).
Theme part
{ "vars": { "all": {}, "dark": { "--tx-bg": "#000" }, "light": { "--tx-bg": "#f0f0f5" } },
"css": "…",
"wallpapers": [ { "id": "dusk", "name": "Dusk", "kind": "fill", "colors": ["#3a1c4a", "#e0643a"], "rotation": 45, "intensity": 0 } ],
"colorThemes": [ { "id": "sunset", "emoji": "🌇", "accent": "orange",
"out": { "dark": ["#cf4339", "#e08a35"], "light": ["#e0483f", "#f09a3a"] },
"wallpapers": { "dark": { "kind": "fill", "colors": ["#2a1030", "#8a3a2a"] }, "light": { "kind": "fill", "colors": ["#ffd9b8", "#ffb48a"] } } } ],
"apply": "sunset" }
Wallpaper: kind fill | pattern (url to an svg); 1–4 colors; rotation degrees (2 colours); intensity negative = dark background (pattern lit by the colours). accent: blue|violet|orange|cyan|green|pink|… (names in app/static/js/core/prefs.js ACCENTS). CSS variables: see app/static/css/tx/tokens.css.
More API (read this before hacking the DOM)
| Need | Use |
|---|---|
| a post is laid out (measure heights, collapse) | tx.ui.onPostRendered((el, post, { height }) => …) — fires two frames after the card is in the DOM; tx.ui.onPost fires immediately |
| the text element of every post | tx.ui.onPostText((textEl, post, card) => …) (class post-text) or slot post.text — for collapse, highlight, translate, table of contents |
| theme changes / colours for a canvas | tx.theme.on('change', (palette) => …) and tx.theme.palette() → { mode, bg, surface, surface2, text, textSecondary, accent, accentFill, glass, separator, red, green } — never poll data-theme |
| a toast with an action (Undo) | tx.toast('Hidden', { action: 'Undo', run: () => … }) (stays ~5.5 s) |
| keyboard shortcuts | tx.keys.add('mod+shift+c', (e) => …) — removed with the mod; plain keys never fire while the user types |
| weather / particles / any full-screen animation | tx.ambient.add({ id, draw(ctx, w, h, dtMs, palette) {…} }) — ONE shared canvas under the app (z-index 2, no clicks) and ONE ≤ 30 fps loop for all mods; cleared for you; off in power-saving mode. Never create your own full-screen canvas or requestAnimationFrame loop. |
| a full-screen page with a Telegram-like header | tx.ui.openScreen({ title, subtitle?, avatar?: svgOrImgHtml, actions?: [{ icon, title, run }], chat?: true, render(box, { footer, setSubtitle, close, el }) {…} }) — chat: true gives a chat layout: wallpaper background, scrolling box, a pinned footer for the composer; setSubtitle('typing…') updates the line under the title |
| emoji that arrive inside user content (AI answers, post text) | tx.emoji.html(escapedHtml) renders them as Apple images. Do not put emoji in your own UI |
| media of a post | tx.media.of(post) → [{ type, url, thumb, duration, size }], tx.media.urls(post) → [url] — never scrape the DOM |
| a list of channels in settings | setting { "key": "quiet", "type": "channels", "title": "…" } → array of channel ids (strings); { "type": "select", "optionsFrom": "channels" } → one id. Channels are in tx.S.channels (id, title) |
| mods that cannot work together | manifest "conflicts": ["other-mod-id"] — the install dialog warns the user (check both mods: declare it in the newer one) |
| a ready-made set of mods (official catalog) | presets in app/static/mods/catalog.json: { id, icon, name{}, description{}, mods: [ids] } — one button installs all |
Code API — tx (argument of export default function (tx); in html parts: TeleXMods['<id>'])
tx.theme.setVars(vars, 'all'|'dark'|'light'),.addCss(css),.addColorTheme(t),.addWallpaper(w),.setWallpaper(id),.select(themeId),.mode()tx.ui.watch(selector, el => …)— run for existing and future elements (MutationObserver);tx.ui.inject(selector, html, where='beforeend');tx.ui.root()tx.ext.addMenu('post', ({post}) => [{label, icon, run}])— item in the post menu ·tx.ext.addMenu('settings', …)— rows in settingstx.ext.addHook('postText', (html, ctx) => html)— sync rewrite of every post's HTML ·tx.ext.on('view', name => …)tx.settings.addRow({title, sub, icon, color, run})·tx.settings.addPage({id, title, sub, icon, render(box)})tx.config(own settings) ·tx.storage.get/set·tx.data[name](json/text parts)tx.S— app state:S.posts,S.channels,S.user, … ·tx.api— all Telegram calls (seeapp/static/js/api.js) ·tx.t,tx.toast(msg),tx.confirm(text, okLabel),tx.escapeHtml
tx.onStop(fn) registers your own cleanup (timers, nodes). Everything registered through tx is removed when the mod is disabled/deleted. Things you create *outside* tx (timers, global listeners, document.body nodes) are your responsibility — for HTML parts the root <div class="tx-mod-root"> is removed automatically, timers are not.
How to build any UI change
1. Find the markup you want to change in app/static/js/** (templates are template-literals) and the styles in app/static/css/tx/*.css. Class prefix tx-; screens: #screen-wall, #screen-settings, #screen-profile, #screen-thread, #screen-channel; dock .tx-dock. 2. Restyle with css/vars parts (no code). Add behaviour with tx.ui.watch(selector, fn). Add markup with tx.ui.inject. 3. The UI re-renders often — never rely on a node surviving; use watch, not a one-off querySelector. 4. Use theme variables (var(--tx-accent), var(--tx-surface), var(--tx-text)) so the mod works in day and night mode.
Checklist before you hand the file over
idvalid and unique;name,version,descriptionfilled;aboutexplains how to use it.- Works in light and dark theme; no hard-coded fonts; touch targets ≥ 40 px (it also runs on phones).
- Settings declared in
manifest.settingswith sane defaults; code reads them viatx.config, never assumes a value. - No network calls to unknown hosts; no secrets; no use of
tx.apibeyond what the mod needs (the user's account is at stake). - Valid JSON (bundle shape) — validate with
node -e "JSON.parse(require('fs').readFileSync('x.module','utf8'))". - Test: serve
app/static(python3 -m http.server 8801 --directory app/static), openindex.html?fake=1, Settings → Mods → paste the file.
Working examples: mods-examples/sunset-theme.module (JSON bundle, theme) · clock-widget.module (HTML + settings) · copy-post-link.module (JS + menus). Full human documentation: docs/mods.md.
Rule 0: no emoji anywhere (UI text, buttons, toasts, names, descriptions, icon). Use the Telegram icon font (<i class="icon icon-NAME"></i>) or inline SVG. Emoji look cheap and break the Telegram feel.
This part explains *how to do it well and why*. A mod that ignores it can overlap the phone's status bar, cover the bottom bar, become unreadable in day mode or (worst case) make the app unusable. The app has an emergency switch (⋮ menu → "Disable all mods", and automatic safe mode after 2 failed starts), but a good mod never needs it.
1. The golden rules (why mods break the app)
1. Never use position: fixed / absolute with top: 0, top: 8px, left: 0; right: 0; height: 100% for something small. On a phone the app is edge-to-edge: the status bar (clock, battery) is drawn *over* the top of the page. Everything near top: 0 hides behind it or collides with it. The real height is var(--tx-safe-top) (≈ 24–48 px, 0 on desktop). The same at the bottom: the gesture bar is var(--tx-safe-bottom), and the app's own dock lives in the bottom ~72 px. → Prefer a slot (tx.ui.add('topbar'|'dock'|'fab'|'post.footer'…)): the app places it correctly on every device. → If you really need a floating element: top: calc(var(--tx-safe-top) + 64px) (below the title bar) or bottom: calc(var(--tx-dock-h) + 24px + var(--tx-safe-bottom)) (above the dock). 2. Never cover the whole screen with a transparent/translucent layer, never set pointer-events: auto on something full-screen, never put overflow: hidden on html/body/#app. A floating widget must be small and may carry pointer-events: none unless it is a button. 3. Never hide or restyle the elements the user needs to leave the screen (.tx-dock, .tx-mainbar, the ⋮ button, settings rows) with display: none or visibility: hidden. 4. Do not use hard-coded colours (#000, #fff, white) for text or surfaces. The app has day and night modes; use the variables from section 3. A white clock on a white day background is invisible. 5. Do not touch html, body, #app, .tx-screen layout properties (display, position, height, transform, filter, overflow, zoom). transform/filter on an ancestor breaks every position: fixed child (the dock jumps, the viewer shifts). backdrop-filter on a large element is expensive: ≤ 3 per screen, never on a scrolling list item. 6. Never write a global rule without a prefix. div { … }, button { … }, * { … }, .icon { … } restyle the whole app. Always scope: .tx-mod-<id> … for your own elements, or an exact app selector. 7. Clean up. Timers (setInterval), global listeners (window.addEventListener), observers: register them with tx.onStop(() => clearInterval(t)). Everything made through tx.ui.* / tx.theme.* is removed automatically. 8. Handle errors. Wrap network/JSON code in try/catch; a mod that throws at start is rejected and removed. Never block: no alert, no endless loops, no synchronous XHR. 9. Touch targets ≥ 40×40 px, text ≥ 13 px. Test at a width of 360 px. 10. One concern per mod. A weather widget must not also restyle the dock.
2. The layout of the app (so that you know where things are)
┌──────────────── phone ────────────────┐
│ status bar (OS) ← var(--tx-safe-top) tall, drawn over the page; NOTHING of yours here
├───────────────────────────────────────┤
│ .tx-mainbar 56 px: stories stack · "TeleX" · search · ⋮ ← slot 'topbar' (end side)
│ #header-search-bar search field ← slot 'search'
│ #feed-tabs All · Media · Popular · Favorites ← slot 'tabs'
│ ┌ post card (.tx-bubble) ───────────┐
│ │ header: avatar · channel · time │ ← slot 'post.header'
│ │ text, photo/video, buttons │
│ │ footer: reactions · views · share │ ← slot 'post.footer' (below text) / 'post.actions' (by share)
│ └───────────────────────────────────┘
│ …scrolls… [fab] ← slot 'fab', ~(dock + 28 px) above the bottom
│ ( Feed Settings Profile ) .tx-dock, 60 px + var(--tx-safe-bottom) ← slot 'dock'
└───────────────────────────────────────┘
Column width on desktop: --tx-column-w = 680 px, centred. Screens: #screen-wall (feed), #screen-settings, #screen-profile, #screen-thread (comments), #screen-channel. Only one screen is visible at a time; the app sets data-view="wall|settings|…" on #app.
Stacking order (z-index) — stay *below* what must stay on top:
| layer | z-index |
|---|---|
| wallpaper | 0–1 |
app content .tx-app | 10 |
| sticky header / tabs | 29–31 |
| dock | 39–40 |
| fab, floating buttons | 38–45 |
| media viewer | 80 |
mod full-screen page (openScreen) | 150 |
| dialogs / confirm | 200 |
| stories viewer | 300 |
| toast | 400 |
A widget that must float over the feed: z-index: 35 (above content and headers, below the dock). Never above 100 unless it is a dialog the user can close.
3. Colours and tokens (the real values)
Use var(--token) — the value changes with day/night mode, accent and wallpaper theme.
| token | night (default) | day | use for |
|---|---|---|---|
--tx-bg | #000000 | #f0f0f5 | page background |
--tx-surface | #1c1c1d | #ffffff | cards, settings groups |
--tx-surface-2 | #262628 | #f2f2f6 | menus, inputs, secondary cards |
--tx-bubble | #212123 | #ffffff | incoming post/message bubble |
--tx-bubble-out | gradient/#2b3e63 | gradient | outgoing bubble |
--tx-glass | rgba(34,34,36,.72) | rgba(255,255,255,.8) | translucent bars (use with backdrop-filter: var(--tx-glass-blur)) |
--tx-glass-border | rgba(255,255,255,.075) | rgba(0,0,0,.08) | 1 px borders of glass |
--tx-separator | rgba(255,255,255,.08) | rgba(0,0,0,.09) | divider lines |
--tx-text | #ffffff | #000000 | main text |
--tx-text-2 | #9d9da3 | #707579 | secondary text, subtitles |
--tx-hint | #6e6e74 | #9a9ea4 | hints, placeholders |
--tx-accent | #7595ff | #3a6fe6 | links, active icons, accent text |
--tx-accent-fill | #5a83f3 | same | filled buttons, active tab |
--tx-accent-soft | accent @16 % | accent @12 % | soft highlight behind accent items |
--tx-red / --tx-green | #ff5b5b / #4fbf6a | #e5484d / #2f9e44 | danger / success |
--tx-bubble-radius | 17px | corner radius of cards | |
--tx-safe-top, --tx-safe-bottom | status bar / gesture bar height | insets — always add them to fixed positions | |
--tx-dock-h | 64px | dock height | |
--tx-font | Roboto stack | font: font-family: var(--tx-font) |
Accent presets (tx.theme.setAccent(fill, day)): blue #5a83f3/#3a6fe6 (default), classic #3e88f7, violet #8774e1, cyan #2fa9c7, green #4fae4e, orange #e88a35, pink #d9608f.
Rules for choosing colours
- Text on
--tx-surface:--tx-text; secondary:--tx-text-2. Never put--tx-text-2on an accent fill. - A custom colour needs a day and a night variant. In a theme part:
vars: { dark: {…}, light: {…} }; in CSS::root[data-theme='light'] .x { … }; in code:tx.theme.mode()returns'dark'|'light'. - Contrast ≥ 4.5:1 for text. Text on a photo/wallpaper needs a translucent surface behind it (
background: var(--tx-glass)), not just a colour. - Keep the accent as the *one* bright colour. Do not use more than 2–3 hues in one mod.
- A translucent surface =
var(--tx-glass)+backdrop-filter: var(--tx-glass-blur)+border: 1px solid var(--tx-glass-border).
4. Skin tokens — restyle the whole app without selectors
When a mod wants a new *look* (glass, neon, paper, flat…), set skin tokens instead of writing CSS for dozens of classes. tx.theme.setSkin(tokens, 'all'|'dark'|'light') turns on the layer; every card, bar, menu, dialog and button then reads these tokens. Unset tokens keep the default.
| group | tokens | affects |
|---|---|---|
| card | --sk-card-bg, -border, -shadow, -filter, -radius | settings groups, post bubbles, profile cards |
| bubble | --sk-bubble-in, --sk-bubble-out, --sk-bubble-radius | message/post bubbles |
| bar | --sk-bar-bg, -border, -shadow, -filter, -radius | dock, header pills, tabs, search |
| menu | --sk-menu-bg, -border, -shadow, -filter, -radius | context menu, reactions strip |
| dialog | --sk-dialog-bg, --sk-dialog-radius | confirm dialogs, sheets |
| button | --sk-button-bg, --sk-button-text, --sk-button-radius | filled buttons |
| chip | --sk-chip-bg, --sk-chip-radius | reactions, small pills |
| misc | --sk-highlight (inner top light), --sk-overlay (dim behind dialogs), --sk-separator, --sk-field-bg |
Always give both modes — a skin that only looks right at night is a bug:
tx.theme.setSkin({ '--sk-card-bg': 'rgba(28,28,32,.55)', '--sk-card-filter': 'blur(18px) saturate(160%)', '--sk-card-border': 'rgba(255,255,255,.08)', '--sk-card-radius': '22px' }, 'dark');
tx.theme.setSkin({ '--sk-card-bg': 'rgba(255,255,255,.62)', '--sk-card-filter': 'blur(18px) saturate(160%)', '--sk-card-border': 'rgba(0,0,0,.06)', '--sk-card-radius': '22px' }, 'light');
If a mod has *setting*s that change a token (blur strength, radius, accent), re-apply in tx.config.on('*', apply).
5. Choosing the right kind of mod (and why)
| Idea | Kind | Why this and not another |
|---|---|---|
| New colours / wallpaper / look | theme part (vars, colorThemes, wallpapers, skin) | no code → can't crash; shown in Settings → Chat settings |
| Small live info (clock, weather, counters) | slot topbar or post.header with html/render | the app positions it; no overlap with the status bar |
| A button that does one thing | slot dock / topbar / fab with icon, title, run | consistent look, 40 px target, removed on disable |
| Extra info on every post | post.footer / post.header / post.actions or ui.onPost | re-applied for posts loaded later (scrolling) |
| Hide / mark posts | ui.onPost + a setting with the words | runs for every post, including new ones |
| Change post text | ext.addHook('postText', html => …) | sync, before render; returns the new HTML |
| Own page (notes, stats, list) | ui.openScreen (+ a dock or topbar button) or settings.addPage | a screen over the app with a back arrow; never inject into other screens |
| AI feature (chat, translate, summarise) | permissions: ["ai"] + tx.ai | built-in, free, uses the user's key — no key handling in the mod |
| Per-mod options | manifest.settings | the app renders the controls and persists the values |
| Snow, rain, stars, any full-screen animation | tx.ambient.add(...) | one shared canvas + one loop for all mods; a private canvas/RAF per mod kills weak phones |
| Floating widget | an html part — only with the safe-area rules of section 1 | last resort |
6. Recipes (complete, copy-paste-safe)
All recipes are sectioned .module files. Keep your own file in the same shape.
6.1 Clock in the top bar (the correct way — no overlap with the status bar)
// @manifest {"id":"topbar-clock","name":{"ru":"Часы","en":"Clock","es":"Reloj","pt":"Relógio","uk":"Годинник"},"version":"1.0.0","author":"you","description":{"ru":"Часы в шапке ленты","en":"A clock in the feed header","es":"Un reloj en la cabecera","pt":"Um relógio no cabeçalho","uk":"Годинник у шапці стрічки"},"icon":"clock","tags":["widget"],"settings":[{"key":"h24","type":"switch","title":{"ru":"24-часовой формат","en":"24-hour format","es":"Formato 24 h","pt":"Formato 24 h","uk":"24-годинний формат"},"default":true}]}
// @part js
export default function (tx) {
function fmt() {
return new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', hour12: !tx.config.get('h24') });
}
tx.ui.add('topbar', {
id: 'clock',
html: '<span class="tx-mod-clock" style="font:500 15px var(--tx-font);color:var(--tx-text-2);padding:0 6px"></span>',
render: function (host) {
var span = host.querySelector('.tx-mod-clock') || host;
var tick = function () { span.textContent = fmt(); };
tick();
var timer = setInterval(tick, 15000);
tx.onStop(function () { clearInterval(timer); });
},
});
}
Why this is right: the slot puts the clock *inside* the 56 px bar that already sits below the status bar, uses theme colours, and stops its timer.
6.2 A tool button + a result dialog
// @manifest {"id":"post-counter","name":{"ru":"Счётчик постов","en":"Post counter","es":"Contador","pt":"Contador","uk":"Лічильник"},"version":"1.0.0","author":"you","description":{"ru":"Показывает, сколько постов загружено","en":"Shows how many posts are loaded","es":"Muestra cuántas publicaciones hay","pt":"Mostra quantas publicações há","uk":"Показує, скільки дописів завантажено"},"icon":"stats"}
// @part js
export default function (tx) {
tx.ui.add('fab', {
id: 'count', icon: 'stats', title: 'Posts',
run: function () { tx.toast(String((tx.S.posts || []).length)); },
});
}
6.3 Filter: hide posts containing words
// @manifest {"id":"word-filter","name":{"ru":"Фильтр слов","en":"Word filter","es":"Filtro","pt":"Filtro","uk":"Фільтр слів"},"version":"1.0.0","author":"you","description":{"ru":"Скрывает посты с заданными словами","en":"Hides posts with chosen words","es":"Oculta publicaciones","pt":"Oculta publicações","uk":"Ховає дописи"},"icon":"hand-stop","settings":[{"key":"words","type":"text","title":{"ru":"Слова через запятую","en":"Words, comma separated","es":"Palabras","pt":"Palavras","uk":"Слова через кому"},"default":""}]}
// @part js
export default function (tx) {
function words() {
return String(tx.config.get('words') || '').toLowerCase().split(',').map(function (w) { return w.trim(); }).filter(Boolean);
}
function check(el, post) {
var text = String((post && (post.text || post.message)) || el.textContent || '').toLowerCase();
el.style.display = words().some(function (w) { return text.indexOf(w) >= 0; }) ? 'none' : '';
}
tx.ui.onPost(check);
tx.onStop(function () { document.querySelectorAll('.tx-bubble[style*="display: none"]').forEach(function (e) { e.style.display = ''; }); });
}
6.4 Post footer: reading time
// @manifest {"id":"read-time","name":{"ru":"Время чтения","en":"Reading time","es":"Tiempo de lectura","pt":"Tempo de leitura","uk":"Час читання"},"version":"1.0.0","author":"you","description":{"ru":"Время чтения под постом","en":"Reading time under a post","es":"Tiempo de lectura","pt":"Tempo de leitura","uk":"Час читання під дописом"},"icon":"timer"}
// @part js
export default function (tx) {
tx.ui.add('post.footer', {
id: 'rt',
render: function (el, ctx) {
var words = String((ctx.post && ctx.post.text) || '').split(/\s+/).filter(Boolean).length;
if (words < 40) { el.style.display = 'none'; return; }
el.style.cssText = 'font-size:12px;color:var(--tx-hint);padding:2px 0';
el.textContent = '⏱ ' + Math.max(1, Math.round(words / 200)) + ' min';
},
});
}
6.5 Own page with saved data (notebook)
// @manifest {"id":"notebook","name":{"ru":"Блокнот","en":"Notebook","es":"Cuaderno","pt":"Caderno","uk":"Блокнот"},"version":"1.0.0","author":"you","description":{"ru":"Заметки в приложении","en":"Notes inside the app","es":"Notas","pt":"Notas","uk":"Нотатки"},"icon":"note"}
// @part js
export default function (tx) {
tx.ui.addDockItem({
id: 'notes', title: 'Notes', icon: 'note',
run: function () {
tx.ui.openScreen({
title: 'Notes',
render: function (box) {
box.innerHTML = '<textarea class="tx-mod-notes" style="width:100%;min-height:50vh;box-sizing:border-box;padding:14px;border-radius:16px;border:1px solid var(--tx-separator);background:var(--tx-surface);color:var(--tx-text);font:16px var(--tx-font);resize:vertical"></textarea>';
var ta = box.querySelector('textarea');
ta.value = tx.storage.get('text') || '';
ta.addEventListener('input', function () { tx.storage.set('text', ta.value); });
},
});
},
});
}
6.6 Theme with skin (glass look, day + night)
// @manifest {"id":"my-glass","name":{"ru":"Стекло","en":"Glass","es":"Cristal","pt":"Vidro","uk":"Скло"},"version":"1.0.0","author":"you","description":{"ru":"Полупрозрачные карточки","en":"Translucent cards","es":"Tarjetas translúcidas","pt":"Cartões translúcidos","uk":"Напівпрозорі картки"},"icon":"brush","tags":["theme"]}
// @part theme
{ "skin": {
"dark": { "--sk-card-bg": "rgba(28,28,32,.55)", "--sk-card-filter": "blur(18px) saturate(160%)", "--sk-card-border": "rgba(255,255,255,.08)", "--sk-bar-bg": "rgba(30,30,34,.6)" },
"light": { "--sk-card-bg": "rgba(255,255,255,.62)", "--sk-card-filter": "blur(18px) saturate(160%)", "--sk-card-border": "rgba(0,0,0,.06)", "--sk-bar-bg": "rgba(255,255,255,.7)" }
} }
6.7 A floating widget, only if a slot does not fit (safe-area aware)
// @manifest {"id":"float-note","name":"Floating note","version":"1.0.0","author":"you","description":"A small note card above the dock","icon":"pin"}
// @part html
<div class="tx-mod-float" style="position:fixed;z-index:35;left:12px;bottom:calc(var(--tx-dock-h) + 24px + var(--tx-safe-bottom));max-width:60vw;padding:8px 12px;border-radius:14px;background:var(--tx-glass);border:1px solid var(--tx-glass-border);backdrop-filter:var(--tx-glass-blur);color:var(--tx-text);font:14px var(--tx-font);pointer-events:none">Hello</div>
Note bottom includes the dock and the gesture inset, pointer-events:none lets taps through, theme colours, small size.
6.8 Make it look like Telegram (official-mod quality)
Official mods should feel native. Reuse the app's look instead of inventing one: bubbles use --tx-bubble / --tx-bubble-out with border-radius: 17px and a 6px corner on the last bubble of a group; glass bars use --tx-glass + --tx-glass-blur; primary buttons are round/pill with --tx-accent-fill; icons come from the icon font (<i class="icon icon-send">, icon-copy, icon-close, icon-more, icon-language, icon-favorite); no emoji at all (use icon-font glyphs; tx.emoji.html exists only to render emoji that arrive inside user content); lists use the .tx-group card look; add an empty state (big emoji + one sentence + a suggestion), a typing indicator (three bouncing dots) while waiting, a Telegram-style toast with Undo for destructive actions, and stream AI answers with tx.ai.stream. See mods-src/ai-chat.js for a complete example.
7. Pitfalls we have seen (do NOT repeat)
- Clock stuck over the status bar:
position:fixed; top:8px; right:8px→ under/over the OS status bar. Use slottopbar, ortop: calc(var(--tx-safe-top) + 64px). - Header "dimmed": a full-width
position:fixed; top:0gradient/overlay laid over the header. Never overlay the top bar; use the--sk-bar-*tokens to change its look. - Everything unreadable in day mode: hard-coded
color:#fff. Usevar(--tx-text). - Dock disappears / jumps:
transform,filter,perspectiveorwill-change: transformset on#app,.tx-screenorbody. Do not. - Mod works once, then vanishes: the app re-renders; a one-off
document.querySelector(...).append(...)is lost. Usetx.ui.add,tx.ui.watch,tx.ui.onPost. - Code breaks after copying from chat: backtick template literals and
${}get mangled. Use'a' + b. Put the whole file in ONE code block. - Three weather mods = three canvases and three animation loops: use
tx.ambient, never your own full-screen canvas orrequestAnimationFrame. - Canvas colours stuck after the theme changes: read
palindraw(ctx,w,h,dt,pal)ortx.theme.palette()every frame/change; never cache colours. - Mod slows the feed: work per post must be O(1); no
querySelectorAll('*'), no layout reads in loops, no network call per post. display:flexon.tx-hiddenetc.: do not override.tx-hidden,.hidden,[hidden].
8. Self-review checklist (do it before answering)
1. Every element I add is inside a slot, or is position:fixed with safe-area maths and z-index ≤ 45, small, and does not cover the title bar, status bar or dock. 2. No selector without a .tx-mod-… prefix or an exact app class; no *, no bare tags. 3. All colours are var(--tx-…)/var(--sk-…), or have a day and a night variant. 4. Timers/listeners are cleaned in tx.onStop. 5. Errors are caught; no use of undocumented tx methods. 6. Manifest is complete (5 languages, icon, version, description); the file is valid (JSON parses / JS module has export default function (tx)). 7. The whole answer is ONE code block; no template literals. 8. Imagine the user installs it on a phone at 360 px width in day mode: is anything covered, cut off or invisible? If unsure, use a slot.