Serenity Operating System
1/*
2 * Copyright (c) 2022, Valtteri Koskivuori <vkoskiv@gmail.com>
3 *
4 * SPDX-License-Identifier: BSD-2-Clause
5 */
6
7#include "StorageModel.h"
8
9#include <AK/FuzzyMatch.h>
10
11namespace Browser {
12
13void StorageModel::set_items(OrderedHashMap<DeprecatedString, DeprecatedString> map)
14{
15 begin_insert_rows({}, m_local_storage_entries.size(), m_local_storage_entries.size());
16 m_local_storage_entries = map;
17 end_insert_rows();
18
19 did_update(DontInvalidateIndices);
20}
21
22void StorageModel::clear_items()
23{
24 begin_insert_rows({}, m_local_storage_entries.size(), m_local_storage_entries.size());
25 m_local_storage_entries.clear();
26 end_insert_rows();
27
28 did_update(DontInvalidateIndices);
29}
30
31int StorageModel::row_count(GUI::ModelIndex const& index) const
32{
33 if (!index.is_valid())
34 return m_local_storage_entries.size();
35 return 0;
36}
37
38DeprecatedString StorageModel::column_name(int column) const
39{
40 switch (column) {
41 case Column::Key:
42 return "Key";
43 case Column::Value:
44 return "Value";
45 case Column::__Count:
46 return {};
47 }
48
49 return {};
50}
51
52GUI::ModelIndex StorageModel::index(int row, int column, GUI::ModelIndex const&) const
53{
54 if (static_cast<size_t>(row) < m_local_storage_entries.size())
55 return create_index(row, column, NULL);
56 return {};
57}
58
59GUI::Variant StorageModel::data(GUI::ModelIndex const& index, GUI::ModelRole role) const
60{
61 if (role != GUI::ModelRole::Display)
62 return {};
63
64 auto const& keys = m_local_storage_entries.keys();
65 auto const& local_storage_key = keys[index.row()];
66 auto const& local_storage_value = m_local_storage_entries.get(local_storage_key).value_or({});
67
68 switch (index.column()) {
69 case Column::Key:
70 return local_storage_key;
71 case Column::Value:
72 return local_storage_value;
73 }
74
75 VERIFY_NOT_REACHED();
76}
77
78TriState StorageModel::data_matches(GUI::ModelIndex const& index, GUI::Variant const& term) const
79{
80 auto needle = term.as_string();
81 if (needle.is_empty())
82 return TriState::True;
83
84 auto const& keys = m_local_storage_entries.keys();
85 auto const& local_storage_key = keys[index.row()];
86 auto const& local_storage_value = m_local_storage_entries.get(local_storage_key).value_or({});
87
88 auto haystack = DeprecatedString::formatted("{} {}", local_storage_key, local_storage_value);
89 if (fuzzy_match(needle, haystack).score > 0)
90 return TriState::True;
91 return TriState::False;
92}
93
94}