Building a Mobile-First H5 AI Chat Assistant: A Practical Guide
This article walks through building a mobile-first H5 AI chat assistant that runs entirely in the browser. It covers a five-layer architecture (build, view, state, rendering, and API access), project structure and baseline build configuration, session state modeling with incremental message appending, streaming response handling with buffering and throttling, a rich-text rendering pipeline for Markdown, syntax highlighting, math formulas, and diagrams, plus theming, mobile viewport adaptation, and performance tuning. A server-side proxy keeps API keys off the client. A pre-launch checklist and extension directions are included.
1. Background and Goals
A mobile-first H5 AI chat assistant is becoming a lightweight entry point for natural language interaction across many business scenarios. Compared with native apps, H5 is install-free, shareable, and fast to iterate. With mature large language model capabilities, the experience of “ask a question and get a structured answer in real time” is finally practical.
The goal of this project is to build a mobile-first chat assistant from scratch that handles session management, streaming output, rich text rendering, and theme adaptation entirely in the browser. On desktop browsers, a fixed-width container simulates a mobile viewport to keep the layout consistent.
One point deserves emphasis: the frontend does not run model inference. It only handles interaction and presentation. Model capabilities are called through a server-side proxy layer, and API keys are never shipped to the client. This is a security baseline that every solution of this kind must follow.
2. Technology Choices and Layered Design
The overall structure has five layers: build, view, state, rendering, and access.
- Build layer: a modern frontend build tool, with pre-bundling and incremental compilation to speed up cold starts and hot updates.
- View layer: single-file components using the Composition API, paired with a mobile component library for the navigation bar, input area, and message bubble list.
- State layer: a centralized store managing the session array, current session ID, loading state, and theme variables.
- Rendering layer: a combined pipeline of Markdown parser, syntax highlighting, math formula plugin, and diagram description language rendering.
- Access layer: a unified request client that handles authentication, timeouts, retries, and streaming chunk reads.
The key benefit of layering is replaceability: once the access layer is abstracted behind a single interface, the model provider can be switched without touching the view or state layers.
3. Project Initialization and Directory Structure
A suggested directory layout (illustrative):
src/api/ # Request wrappers and streaming readsstores/ # Session and theme statecomponents/ # Bubbles, input box, code blockscomposables/ # Theme, scrolling, rendering logicutils/ # Markdown and formula rendering pipelineviews/ # Main chat page
Pin down a few baseline settings during initialization: point the path alias at src; enable LAN access on the dev server for on-device debugging; enable asset chunking in the production build so heavy dependencies such as the highlighting library and diagram renderer are split into async chunks, leaving only essential code in the first load.
4. Session State Management and Interaction Modeling
The state of a chat assistant is not complex, but it can easily get out of control. Three things matter: the session list, the message stream, and the request lifecycle.
export const useChatStore = defineStore('chat', {state: () => ({sessions: [],currentId: null,pending: false,theme: 'light'}),getters: {currentMessages: (s) =>s.sessions.find(item => item.id === s.currentId)?.messages ?? []},actions: {ensureSession() { /* Create a session and set it current if none exists */ },pushMessage(msg) { /* Append a user or assistant message */ },appendDelta(text) { /* Concatenate incremental text to the last assistant message */ },finish() { this.pending = false }}})
The key is incremental concatenation rather than full replacement. In a streaming scenario, overwriting with the complete text every time causes list reflow and scroll jumps. Appending increments to the last message, together with bottom-anchoring that scrolls when content length changes, produces a stable typewriter effect.
5. Key Implementation of Streaming Chat
Mainstream LLM APIs generally offer a streaming mode with chunked transfer. The frontend’s job is to reconstruct text increments from the byte stream.
const res = await fetch('/api/chat', {method: 'POST',headers: { 'Content-Type': 'application/json' },body: JSON.stringify({ messages, stream: true })})const reader = res.body.getReader()const decoder = new TextDecoder()let buffer = ''while (true) {const { value, done } = await reader.read()if (done) breakbuffer += decoder.decode(value, { stream: true })const lines = buffer.split('\n')buffer = lines.pop() // Keep the tail line that may be truncatedfor (const line of lines) {if (!line.startsWith('data:')) continueconst payload = line.slice(5).trim()if (payload === '[DONE]') continueconst delta = JSON.parse(payload)?.choices?.[0]?.delta?.contentif (delta) store.appendDelta(delta)}}
Four edge cases must be handled in practice. First, a chunk may cut a complete data line in half, so a buffer is needed to hold the tail line. Second, network interruptions require timeout and retry strategies. Third, if the user switches sessions or submits repeatedly while generation is in progress, request identifiers are needed for idempotency control. Fourth, rendering must be throttled by merging high-frequency increments per frame, so that every single character does not trigger a full re-render.
The server-side proxy layer should do three things: keep API keys only in server-side environment variables; apply basic limits on input length and request frequency; inject the system prompt centrally instead of scattering it across the client.
6. Rich Text Rendering Pipeline
Assistant answers commonly include headings, lists, tables, code blocks, math formulas, and diagram descriptions. The rendering pipeline is best split into four stages:
- Parse Markdown into a token sequence.
- Hand code blocks to a syntax highlighter for per-language coloring.
- Pass formula fragments to a math formula plugin that converts them into displayable layout structures.
- Once the matching language identifier is detected, render diagram description text into graphics asynchronously.
import MarkdownIt from 'markdown-it'import hljs from 'highlight.js'const md = new MarkdownIt({ html: false, linkify: true, breaks: true })md.renderer.rules.fence = (tokens, idx) => {const t = tokens[idx]const code = hljs.highlight(t.content, { language: t.info.trim() || 'plaintext' }).valuereturn `<pre class="code-block"><code class="hljs">${code}</code></pre>`}
Two security rules are non-negotiable: disable raw HTML insertion, and run the rendered output through a unified sanitization step so malicious tags in model output cannot create injection risks. Overlay copy and download buttons on code blocks, bound through event delegation to avoid registering listeners again on every render.
7. Theming, Mobile Adaptation, and Performance Details
Theming uses semantic variables with two sets of values. Define semantic names such as background, elevated background, primary text, secondary text, border, and accent color, then give each a light and a dark value. Switching themes only replaces the variables on the root node; component styles never hardcode colors, which avoids changing class names component by component.
Mobile adaptation focuses on three points: use safe-area variables to handle notches and the bottom home indicator; keep the input area fixed at the bottom and reposition it when the virtual keyboard opens; pair bottom-anchoring with incremental content in long lists, while letting users pause auto-anchoring after scrolling up so reading is not interrupted.
For performance, long sessions should use virtual scrolling or segmented rendering; highlighting and diagram rendering results should be cached by content hash; all non-first-screen dependencies should load asynchronously.
8. Verification Checklist and Extension Directions
Before launch, self-test item by item: retry behavior and messaging under weak or no network; repeated submission and session switching during generation; scrolling performance with very long code blocks and very large tables; formula and diagram contrast in dark mode; accessibility basics such as focus order and sufficient contrast.
Possible extensions include session export and search, multimodal input, prompt template management, and extracting the rendering pipeline into a standalone module for reuse across multiple platform containers. Overall, once the access layer is cleanly abstracted and incremental concatenation plus render throttling are solid, a stable, usable mobile AI chat assistant takes shape.
