Ladybird: Implement JS console input history

One can now use KeyUp and KeyDown to navigate through the already run
commands in the JS console.
This commit is contained in:
Sebastian Zaha 2023-07-19 14:27:30 +02:00 committed by Linus Groh
parent 6f15b92ace
commit 8e8f124ca9
Notes: sideshowbarker 2024-07-18 00:54:03 +09:00
2 changed files with 64 additions and 15 deletions

View File

@ -13,6 +13,7 @@
#include <AK/StringBuilder.h>
#include <LibJS/MarkupGenerator.h>
#include <QFontDatabase>
#include <QKeyEvent>
#include <QLineEdit>
#include <QPalette>
#include <QPushButton>
@ -45,24 +46,10 @@ ConsoleWidget::ConsoleWidget()
layout()->addWidget(bottom_container);
m_input = new QLineEdit(bottom_container);
m_input = new ConsoleInputEdit(bottom_container, *this);
m_input->setFont(QFontDatabase::systemFont(QFontDatabase::FixedFont));
bottom_container->layout()->addWidget(m_input);
QObject::connect(m_input, &QLineEdit::returnPressed, [this] {
auto js_source = ak_deprecated_string_from_qstring(m_input->text());
if (js_source.is_whitespace())
return;
m_input->clear();
print_source_line(js_source);
if (on_js_input)
on_js_input(js_source);
});
setFocusProxy(m_input);
auto* clear_button = new QPushButton(bottom_container);
@ -184,4 +171,48 @@ void ConsoleWidget::reset()
m_waiting_for_messages = false;
}
void ConsoleInputEdit::keyPressEvent(QKeyEvent* event)
{
switch (event->key()) {
case Qt::Key_Down: {
auto last_index = m_history.size() - 1;
if (m_history_index < last_index) {
m_history_index++;
setText(qstring_from_ak_deprecated_string(m_history.at(m_history_index)));
} else if (m_history_index == last_index) {
m_history_index++;
clear();
}
break;
}
case Qt::Key_Up:
if (m_history_index > 0) {
m_history_index--;
setText(qstring_from_ak_deprecated_string(m_history.at(m_history_index)));
}
break;
case Qt::Key_Return: {
auto js_source = ak_deprecated_string_from_qstring(text());
if (js_source.is_whitespace())
return;
if (m_history.is_empty() || m_history.last() != js_source) {
m_history.append(js_source);
m_history_index = m_history.size();
}
clear();
m_console_widget.print_source_line(js_source);
if (m_console_widget.on_js_input)
m_console_widget.on_js_input(js_source);
break;
}
default:
QLineEdit::keyPressEvent(event);
}
}
}

View File

@ -12,6 +12,7 @@
#include <AK/DeprecatedString.h>
#include <AK/Function.h>
#include <AK/Vector.h>
#include <QLineEdit>
#include <QWidget>
class QLineEdit;
@ -48,4 +49,21 @@ private:
bool m_waiting_for_messages { false };
};
class ConsoleInputEdit final : public QLineEdit {
Q_OBJECT
public:
ConsoleInputEdit(QWidget* q_widget, ConsoleWidget& console_widget)
: QLineEdit(q_widget)
, m_console_widget(console_widget)
{
}
private:
virtual void keyPressEvent(QKeyEvent* event) override;
ConsoleWidget& m_console_widget;
Vector<DeprecatedString> m_history;
size_t m_history_index { 0 };
};
}