Skip to content

Commit 7cba2e9

Browse files
committedFeb 13, 2014
component/autocomplete: add local completions
1 parent 918c84f commit 7cba2e9

File tree

1 file changed

+42
-10
lines changed

1 file changed

+42
-10
lines changed
 

‎opal/lissio/component/autocomplete.rb

+42-10
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,8 @@ class Autocomplete < Lissio::Component
77
class Section < Lissio::Component
88
class Options
99
def initialize(&block)
10-
@key = :id
10+
@key = :id
11+
@limit = 10
1112

1213
if block.arity.nonzero?
1314
block.call(self)
@@ -20,14 +21,22 @@ def title(value = nil)
2021
value ? @title = value : @title
2122
end
2223

23-
def url(value = nil)
24-
value ? @url = value : @url
24+
def local(value = nil)
25+
value ? @local = value : @local
26+
end
27+
28+
def remote(value = nil)
29+
value ? @remote = value : @remote
2530
end
2631

2732
def key(value = nil)
2833
value ? @key = value : @key
2934
end
3035

36+
def limit(value = nil)
37+
value ? @limit = value : @limit
38+
end
39+
3140
def select(&block)
3241
block ? @select = block : @select
3342
end
@@ -103,10 +112,12 @@ def section(&block)
103112
end
104113

105114
@autocompleters << {
106-
url: options.url,
107115
title: options.title,
108-
select: options.select,
116+
local: options.local,
117+
remote: options.remote,
109118
key: options.key,
119+
limit: options.limit,
120+
select: options.select,
110121
section: section
111122
}
112123
end
@@ -132,15 +143,25 @@ def query
132143
remove_old_completions
133144

134145
comps = @autocompleters.map do |ac|
135-
url = "#{ac[:url]}?q=#{query.value}"
146+
local_completions = get_local_completions(ac)
136147

137-
Browser::HTTP.get(url).then do |response|
138-
[ac, response]
148+
if local_completions.count < ac[:limit] and ac[:remote]
149+
url = "#{ac[:remote]}?q=#{query.value}"
150+
151+
Browser::HTTP.get(url).then do |response|
152+
[ac, local_completions, response]
153+
end
154+
else
155+
[ac, local_completions, nil]
139156
end
140157
end
141158

142-
Promise.when(*comps).each do |ac, response|
143-
append_completions(ac, response.json)
159+
Promise.when(*comps).each do |ac, completions, response|
160+
if response
161+
completions += response.json.take(ac[:limit] - completions.size)
162+
end
163+
164+
append_completions(ac, completions)
144165
end
145166
end
146167

@@ -190,6 +211,17 @@ def set_hint(comps, ac)
190211
end
191212
end
192213

214+
def get_local_completions(ac)
215+
return [] unless ac[:local]
216+
217+
key = ac[:key]
218+
q = query.value
219+
220+
ac[:local].select do |comp|
221+
comp[key].match(q)
222+
end.take(ac[:limit])
223+
end
224+
193225
def append_completions(ac, comps)
194226
if comps.empty?
195227
hide_completions unless @some_results

0 commit comments

Comments
 (0)
Please sign in to comment.