#include "config.h"
#include "TypeAhead.h"
#include "KeyboardEvent.h"
#include <wtf/unicode/CharacterNames.h>
namespace WebCore {
using namespace WTF::Unicode;
TypeAhead::TypeAhead(TypeAheadDataSource* dataSource)
: m_dataSource(dataSource)
, m_repeatingChar(0)
{
}
static const Seconds typeAheadTimeout { 1_s };
static String stripLeadingWhiteSpace(const String& string)
{
unsigned length = string.length();
unsigned i;
for (i = 0; i < length; ++i) {
if (string[i] != noBreakSpace && !isSpaceOrNewline(string[i]))
break;
}
return string.substring(i, length - i);
}
int TypeAhead::handleEvent(KeyboardEvent* event, MatchModeFlags matchMode)
{
if (event->timeStamp() < m_lastTypeTime)
return -1;
int optionCount = m_dataSource->optionCount();
Seconds delta = event->timeStamp() - m_lastTypeTime;
m_lastTypeTime = event->timeStamp();
UChar c = event->charCode();
if (delta > typeAheadTimeout)
m_buffer.clear();
m_buffer.append(c);
if (optionCount < 1)
return -1;
int searchStartOffset = 1;
String prefix;
if (matchMode & CycleFirstChar && c == m_repeatingChar) {
prefix = String(&c, 1);
m_repeatingChar = c;
} else if (matchMode & MatchPrefix) {
prefix = m_buffer.toString();
if (m_buffer.length() > 1) {
m_repeatingChar = 0;
searchStartOffset = 0;
} else
m_repeatingChar = c;
}
if (!prefix.isEmpty()) {
int selected = m_dataSource->indexOfSelectedOption();
int index = (selected < 0 ? 0 : selected) + searchStartOffset;
index %= optionCount;
String prefixWithCaseFolded(prefix.foldCase());
for (int i = 0; i < optionCount; ++i, index = (index + 1) % optionCount) {
String text = m_dataSource->optionAtIndex(index);
if (stripLeadingWhiteSpace(text).foldCase().startsWith(prefixWithCaseFolded))
return index;
}
}
if (matchMode & MatchIndex) {
bool ok = false;
int index = m_buffer.toString().toInt(&ok);
if (index > 0 && index <= optionCount)
return index - 1;
}
return -1;
}
}