The vocabulario feature module is the heart of ComuniTEA’s communication layer. It packages every hook needed to build and manage a child’s personal vocabulary: audio playback, PECS-style game progression, custom pictogram CRUD, sentence logging, AI-powered phrase expansion, AI-driven reordering of pictograms by usage frequency, support-team management, and guided activity sequences. All exports are available through the single barrel file atDocumentation Index
Fetch the complete documentation index at: https://mintlify.com/ElthonJohan/comunitea/llms.txt
Use this file to discover all available pages before exploring further.
features/vocabulario/index.ts, which re-exports data types, vocabulary data constants, the pictogram asset catalog, and all hooks described below.
useSpeech
useSpeech is the audio playback hook for all pictogram speech in the app. It implements a three-tier fallback chain: bundled MP3 clip → ElevenLabs neural TTS (via the elevenlabs-tts Edge Function) → expo-speech system TTS. Voice gender (masculine or feminine) is read from the global useVoice() context, and playback speed comes from parental settings (tts_speed, default 1.0).
Return shape
Speaks a single pictogram. If
id is provided and a bundled MP3 clip exists for that ID in the current voice profile, the clip is played. Otherwise falls through to ElevenLabs / system TTS.Iterates over an array of
Pictogram objects and calls speak(item.text, item.id) sequentially. Used for reading multi-word sentences aloud.Speaks an arbitrary string through ElevenLabs (or system TTS fallback). Used by the Magic Expand feature after the AI generates an expanded sentence.
Tablero-specific variant: stops any running phrase playback first, then resolves
assetKey from the audio asset catalog. If no bundled clip is found, falls back to ElevenLabs/system TTS with text.Pauses the
expo-audio player and calls Speech.stop() to halt any in-progress system TTS.Fallback chain
Usage example
When the device is offline (
isConnected === false), useSpeech skips the ElevenLabs network call entirely and routes directly to expo-speech. No error is thrown and no alert is shown.useGame
useGame manages the PECS-style pictogram matching game. It loads the child’s current sub-level from the game_progress table, persists completed sessions to game_sessions, and evaluates the advancement criterion automatically.
Parameters — saveSession
Number of correct answers in the just-completed session.
Total number of trials in the session.
The sub-level being played (1–5). Passed explicitly to avoid stale-closure bugs.
Recent sessions at the same sub-level, loaded by
load() into recentSessionsAtLevel.Return shape
Current PECS sub-level (1–5). Defaults to
1 before load() resolves.true while the initial query to game_progress is in flight.Fetches the most-recent
game_progress row and the last 5 sessions at that sub-level. Call this once on mount.Persists the session and evaluates advancement. Returns
{ advanced, newSublevel, performanceDrop }.Allows a parent or therapist to manually set the child’s sub-level. Inserts a new
game_progress row.The last 5 sessions at the current sub-level, used to evaluate the advancement criterion.
Advancement criterion
supabase.rpc('upsert_ai_insight', ...) to record a sublevel_ready insight for the caregivers’ report.
Usage example
useCustomPictograms
useCustomPictograms manages the “Mi Mundo en Fotos” feature — user-created pictograms stored in the custom_pictograms Supabase table. It accepts a categoryKey filter, automatically loads pictograms on mount, and pre-warms the offline picture cache after loading.
Parameters
The active vocabulary category to filter by (e.g.
"comida", "juguetes"). Pass null to skip loading — returns an empty array.Return shape
All custom pictograms for the authenticated user in the given
categoryKey, ordered by created_at ascending.true while the Supabase query is in flight.Inserts a new
custom_pictograms row. imageUrl must be the public URL returned by Supabase Storage after uploading. The new pictogram is appended to the local state optimistically.Removes the pictogram from local state immediately (optimistic), deletes the Storage file from the
pictograms bucket, removes the cached local URI, and deletes the database row.Re-fetches from Supabase. Useful after uploading a new image from another screen.
CustomPictogram shape
Usage example
usePictogramHistory
usePictogramHistory provides a personalized next-pictogram predictor. It loads the child’s last 500 sentences from sentence_log, builds a co-occurrence map (global and time-of-day segmented), and exposes getSuggestions() to predict which pictogram should come next. If fewer than 20 sentences have been recorded, it falls back to a static COOCCURRENCES constant.
Return shape
Returns up to
limit (default 3) pictogram IDs that most frequently follow lastId. Excludes IDs already in existingIds. Uses the time-of-day sub-map when the current turn has ≥ 5 recorded sentences; otherwise uses the global map.true after the initial Supabase query resolves.Total sentences loaded (up to 500 most recent).
Sentence count broken down by
'morning' (06:00–12:00), 'afternoon' (12:00–18:00), and 'evening' (18:00–06:00).Returns the current time-of-day bucket based on the device clock.
Usage example
useSentenceHistory
useSentenceHistory loads the child’s saved sentence history from the sentence_log table for display in the “Mis oraciones” list view. It fetches the 50 most recent entries ordered newest-first.
Return shape
Up to 50 most recent sentence log entries, ordered by
created_at descending.true on initial load and while refresh() is in flight.Error message string from Supabase if the query fails, otherwise
null.Re-fetches the sentence history. Resets the error state before querying.
SentenceLogEntry shape
Usage example
useMagicExpand
useMagicExpand encapsulates the “magic wand” AI phrase expansion feature. It reads the current sentence from the global useSentence() store, sends the pictogram labels to the ai-expand Edge Function, speaks the expanded text aloud, and logs the event to usage stats.
Return shape
Triggers the expansion flow. No-op if the sentence is empty or a request is already in flight. Handles session token refresh automatically. Shows an
Alert on network or server errors.true while the Edge Function request is pending. Use this to show a loading indicator on the wand button.Request sent to ai-expand
Usage example
useAIAdaptation
useAIAdaptation is the client-side AI engine (Phase 8). On mount it fetches up to 1,000 sentence log rows from the last 30 days, calculates per-pictogram usage frequency, detects patterns (sentence length trends, unused categories, common pictogram pairs), writes ai_insights records via RPC, and exposes a getOrderedItems() sorter.
Return shape
Sorts leaf vocabulary items (those without sub-items) by frequency of use, with a time-of-day boost (+3 to effective frequency) for contextually relevant pictograms. Branch (subcategory) items are preserved at the front to maintain navigation structure. Returns the original order when no frequency data is available yet.
Up to 5 non-expired AI insights from the
ai_insights table, sorted by unseen-first then newest-first. Each entry has id, insight_type, message, seen, and created_at.Removes the insight from local state immediately and updates
seen = true in the database.true after analysis and insight loading complete.Map of
pictogramId → useCount over the last 30 days.AIInsight shape
Time-of-day boost table
| Time window | Boosted pictogram IDs |
|---|---|
| 06:00–10:00 (morning) | dientes, bano, ducha, desayuno, leche, tostada, mochila, escuela |
| 10:00–14:00 (midday) | almuerzo, comer, agua, clase, libro, jugar |
| 14:00–19:00 (afternoon) | merienda, jugar, pelota, musica, television, parque |
| 19:00–22:00 (evening) | cena, bano, pijama, cuento, dormir |
| 22:00–06:00 (night) | dormir, silencio, osito |
Usage example
useChildTeam
useChildTeam manages the support team (therapists, psychologists, teachers, parents) for the active child profile. Invitations are stored in the child_team table with a secure token; invited members accept via the accept_team_invite RPC. All team mutations write to the config_audit_log via auditLog().
TeamRole values and default permissions
| Role | Label | can_view_reports | can_edit_vocabulary |
|---|---|---|---|
padre_madre | 👨👩👧 Padre / Madre | ✅ | ✅ |
terapeuta | 🏥 Terapeuta | ✅ | ✅ |
psicologo | 🧠 Psicólogo / a | ✅ | ❌ |
docente | 🏫 Docente | ✅ | ❌ |
Return shape
All team members for the active child profile, ordered by
created_at ascending.Creates a
pending invitation with a random invite token. The token is shown to the inviting parent so they can share it with the professional out-of-band. Returns the new TeamMember record or null on error.Called by the professional when they enter the invite token. Calls the
accept_team_invite Supabase RPC. Returns null on success, or an error message string.Sets the member’s status to
'revoked'. The member loses access but the record is preserved for audit purposes.Creates a 7-day share token in the
share_tokens table (cleans up expired tokens first). Returns the token string or null on error.Usage example
useDisabledPictograms
useDisabledPictograms lets a parent hide individual pictograms from the child’s boards. The disabled set is persisted in AsyncStorage for instant offline read access. Every toggle writes a best-effort entry to the config_audit_log via auditLog().
Return shape
The set of currently hidden pictogram IDs. Populated from
AsyncStorage on mount.Returns
true if the pictogram with id is currently hidden. Safe to call before loaded is true (returns false).Adds the ID to the disabled set if it was enabled, or removes it if it was disabled. Persists to
AsyncStorage and appends an audit log row.true after the AsyncStorage read completes on mount. Filter pictogram grids only once loaded is true to avoid a flash of all pictograms.Usage example
useActivities
useActivities manages guided activity sequences stored in the guided_activities table. Each activity has a name, a type, and an ordered list of pictogram steps. Completed activity sessions are recorded in activity_sessions for inclusion in caregiver reports.
Types
Return shape
All activities for the current user, ordered by
created_at descending (newest first).Inserts a new activity and prepends it to local state. Returns the created activity or
null on error.Deletes the activity from the database and removes it from local state.
Records a completed (or partial) activity session in
activity_sessions. This data feeds into caregiver reports.Usage example
Offline Queue
When the device is offline, Supabase writes for usage stats and sentence logs are deferred vialib/offlineQueue.ts. The queue is persisted in AsyncStorage under the key 'offline_event_queue' and flushed automatically by NetworkContext when connectivity is restored.
Offline event captured
A stat or sentence event is recorded locally via
enqueueEvent(event). The app continues working normally.Batch insert
flushQueue() splits queued events by type and performs two Promise.allSettled inserts — one into usage_stats and one into sentence_log.