⌨️ Type Anything

Universal Spotlight, Shortcut Tokenizer & Rich Text Input Controls with Natural Syntax Parsing for Flutter.

pub package pub points license platform WASM Ready


🌟 Overview

Modern productivity tools like Linear, Todoist, and Notion rely on power-user input bars where users type shortcuts (#Project, @Assignee, !Priority, ~Duration) or natural language expressions directly into a single text field.

Traditionally, implementing this in Flutter brings several critical pain points:

  1. Multi-word Boundary Collisions: Naive regex tokenizers break when hashtags or mentions contain spaces (e.g. #Project Titan or @Jane Doe), bleeding into adjacent words or symbols.
  2. Layout Deformation: Placing dropdown suggestions inside Column widgets pushes surrounding form fields, breaking bottom sheets and mobile keyboards.
  3. UI Framework Lock-in: Hardcoded styles force developers to fork packages just to match their Design System (Material 3, Cupertino, Adaptive UI, Theta UI).
  4. Monolithic Coupling: Mixing domain logic with UI widgets prevents using the same tokenizer in background jobs, headless CLI tools, or BLoC state machines.

type_anything solves these challenges with a clean, modular architecture:

  • ⚡ Dual-Engine Design: Independent Headless Lexer (TypeTokenizer) and Flutter UI Controls (TypeAnythingField).
  • 🎯 Boundary-Safe Multi-Word Matching: Tokenize entity names with spaces accurately without regex bleeding.
  • 🔭 Tentative Lookahead Scoping: Seamless power-user query window (up to 3 non-matching words allowed after longest fit token) modeled after Todoist & Linear.
  • 🪟 Floating Overlay Engine: Uses Flutter's CompositedTransformFollower to float suggestions seamlessly above or below without deforming the widget tree.
  • 🎨 Slot-Driven Theming: Fully customize item tiles, floating containers, and chip spans via TypeAnythingTheme.
  • 🌐 Built-in Universal Detectors: Out-of-the-box support for Date/Time phrases in English & Vietnamese, Priority (!1, !2), and Duration (~15m, ~1h).
  • 🧮 Pure Algorithm Core: Isolated string algorithms (BoundaryGuard, LongestValidMatchScanner, TentativeLookaheadEvaluator, TextCleaner) for 100% testable, zero-coupling logic.

✨ Key Features

  • 🏷️ Multi-Word Shortcut Support: Parse #Mobile App or @Nguyen Van A without breaking syntax boundaries.
  • ⌨️ Desktop & Keyboard Accessibility: Built-in keyboard navigation (Arrow Down, Arrow Up, Enter, Tab, Escape).
  • 🕒 Universal Temporal Parser: Parse relative dates (today, tomorrow, weekend, weekdays, hôm nay, ngày mai, thứ 2 - chủ nhật).
  • 🧩 Zero-Coupling SOLID Design: 1 class per file, clean separation of Domain, Data, and Presentation.
  • 🔌 Composition or Subclassing: Use TypeAnythingProvider for clean OOP or TypeRegistryProvider for rapid composition.
  • 🚀 WASM-Ready & Multiplatform: 100% pure Dart & Flutter compatibility across Android, iOS, macOS, Windows, Linux, and Web.

📐 Architecture & Flow

sequenceDiagram
    autonumber
    actor User as User
    participant Field as TypeAnythingField
    participant Ctrl as TypeEditingController
    participant Engine as TypeTokenizer
    participant Provider as TypeAnythingProvider
    participant Overlay as TypeSuggestionOverlay

    User->>Field: Types text "#Mobile"
    Field->>Ctrl: Key strokes & cursor offset
    Ctrl->>Engine: buildTextSpan() triggers tokenize()
    Engine->>Provider: isValidToken() check boundaries
    Engine-->>Ctrl: Returns List<TypeMatchToken>
    Ctrl-->>Field: Renders highlighted TextSpans / Chips
    
    Field->>Provider: search(ruleType, query) with debounce
    Provider-->>Field: Returns List<TypeMatchItem>
    Field->>Overlay: Show floating dropdown
    User->>Overlay: Select item (Tap or Enter/Tab)
    Overlay->>Ctrl: applySuggestion(item)
    Field->>Overlay: Dismiss overlay

🚀 Getting Started

Add type_anything to your pubspec.yaml:

flutter pub add type_anything

Import the package:

import 'package:type_anything/type_anything.dart';

💡 Practical Usage & Recipes

Recipe 1: Minimal Quickstart (Subclassing Provider)

import 'package:flutter/material.dart';
import 'package:type_anything/type_anything.dart';

class TaskInputProvider extends TypeAnythingProvider {
  @override
  List<ShortcutRule> get rules => const [
        ShortcutRule(
          ruleType: 'project',
          prefix: '#',
          defaultColor: Colors.blue,
        ),
        ShortcutRule(
          ruleType: 'assignee',
          prefix: '@',
          isMultiple: true,
          defaultColor: Colors.teal,
        ),
        BuiltinRules.priority,
      ];

  @override
  Future<List<TypeMatchItem>> search(String ruleType, String query) async {
    if (ruleType == 'project') {
      return [
        const TypeMatchItem(
          id: 'p1',
          label: 'Mobile App',
          searchKey: 'mobile app',
          value: 'proj_mobile',
        ),
      ];
    }
    return [];
  }
}

class QuickAddPage extends StatelessWidget {
  final provider = TaskInputProvider();
  late final controller = TypeEditingController(provider: provider);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Padding(
        padding: const EdgeInsets.all(16),
        child: TypeAnythingField(
          controller: controller,
          placeholder: 'What needs doing? #Project @assignee !1',
          onSubmitted: (value) async {
            final tokenizer = TypeTokenizer(provider: provider);
            final result = await tokenizer.extract(value);
            print('Clean Title: ${result.cleanTitle}');
            print('Entities: ${result.entities}');
          },
        ),
      ),
    );
  }
}

Recipe 2: Composition Mode (TypeRegistryProvider)

If you prefer passing rules dynamically without defining a new class:

final provider = TypeRegistryProvider(
  rules: const [
    ShortcutRule(prefix: '#', ruleType: 'tag', defaultColor: Colors.purple),
    BuiltinRules.command,
  ],
  onSearch: (ruleType, query) async {
    // Return candidate items dynamically
    return [];
  },
);

final controller = TypeEditingController(provider: provider);

Recipe 3: Slot-Driven Custom Styling (TypeAnythingTheme)

Customizing chip spans and dropdown tiles to match your design system:

TypeAnythingField(
  controller: controller,
  theme: TypeAnythingTheme(
    overlayMaxHeight: 280,
    borderRadius: BorderRadius.circular(16),
    // Custom item tile in dropdown
    itemTileBuilder: (context, item, isSelected, onTap) {
      return ListTile(
        selected: isSelected,
        leading: Icon(item.icon ?? Icons.label),
        title: Text(item.label),
        subtitle: item.subtitle != null ? Text(item.subtitle!) : null,
        onTap: onTap,
      );
    },
    // Custom inline badge chip
    chipSpanBuilder: (context, token, baseStyle) {
      return WidgetSpan(
        alignment: PlaceholderAlignment.middle,
        child: Container(
          padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
          decoration: BoxDecoration(
            color: Colors.blue.withValues(alpha: 0.15),
            borderRadius: BorderRadius.circular(6),
          ),
          child: Text(token.rawToken, style: const TextStyle(color: Colors.blue)),
        ),
      );
    },
  ),
);

⚙️ Configuration Reference

TypeAnythingField Options

Parameter Type Default Description
controller TypeEditingController Required Controls text value, tokenization and spans.
placeholder String '' Placeholder hint text when field is empty.
theme TypeAnythingTheme? null Slot theme for customizing overlay and chips.
debounceDuration Duration 150ms Debounce time before dispatching search queries.
showSuggestionsAbove bool false Whether suggestions float above the text field.
borderless bool false When true, removes default background container.
overlayOffset Offset Offset(0, 6) Distance between text field and suggestion overlay.
onIntentSelected Function(String, String)? null Callback when intent-flagged item is selected.

ShortcutRule Options

Property Type Default Description
ruleType String Required Unique key identifying the rule (e.g. 'project', 'tag').
prefix String Required Trigger prefix symbol (e.g. '#', '@').
isMultiple bool false Whether multiple tokens of this rule are allowed.
allowSpaces bool false Whether tokens may contain spaces (e.g. #Mobile App).
requiresExactEntityMatch bool false When true, only highlights confirmed database entities.
defaultColor Color? null Default highlight color for tokens matching this rule.

📄 License

This package is released under the MIT License.

Libraries

type_anything