@@ -1187,6 +1187,14 @@ def set(
11871187 """
11881188 Sets the selected option(s) of the input selectize.
11891189
1190+ Selected items are altered as follows:
1191+ 1. Click on the selectize input to open the dropdown.
1192+ 2. For items that are currently selected but are not in `selected`, remove them
1193+ (starting from the end) by selecting the item and pressing the `"Delete"` key.
1194+ 3. For items that are not currently selected but are in `selected`, click on the
1195+ option in the dropdown (which adds it to the selected list).
1196+ 4. Press the `"Escape"` key to close the dropdown.
1197+
11901198 Parameters
11911199 ----------
11921200 selected
@@ -1197,34 +1205,38 @@ def set(
11971205 if isinstance (selected , str ):
11981206 selected = [selected ]
11991207 self ._loc_events .click ()
1208+ desired_set = set (selected )
12001209
12011210 currently_selected : list [str ] = []
1202- selected_items = self ._loc_events .locator ("> .item" )
1203- for i in range (selected_items .count ()):
1204- item = selected_items .nth (i )
1205- data_value = item .get_attribute ("data-value" )
1206- if data_value :
1211+ selected_item_locs = self ._loc_events .locator ("> .item" ).all ()
1212+ # Reverse to remove them starting from the end / make stable
1213+ selected_item_locs .reverse ()
1214+
1215+ # Remove items that are currently selected but not in the desired set
1216+ for selected_item_loc in selected_item_locs :
1217+ data_value = selected_item_loc .get_attribute ("data-value" )
1218+ if not data_value :
1219+ continue
1220+
1221+ if data_value not in desired_set :
1222+ selected_item_loc .click ()
1223+ self .page .keyboard .press ("Delete" )
1224+ else :
12071225 currently_selected .append (data_value )
12081226
1227+ # Add items that are in the desired set but not currently selected
12091228 current_set = set (currently_selected )
1210- desired_set = set (selected )
1229+ # Use the `selected` list to preserve the order of items
1230+ for data_value in selected :
1231+ if data_value in current_set :
1232+ continue
12111233
1212- for current_value in currently_selected :
1213- if current_value not in desired_set :
1214- item_to_remove = self ._loc_events .locator (
1215- f"> .item[data-value='{ current_value } ']"
1216- )
1217- if item_to_remove .count () > 0 :
1218- item_to_remove .click ()
1219- self .page .keyboard .press ("Delete" )
1220-
1221- for value in selected :
1222- if value not in current_set :
1223- self ._loc_selectize .locator (f"[data-value='{ value } ']" ).click (
1224- timeout = timeout
1225- )
1234+ self ._loc_selectize .locator (f"[data-value='{ data_value } ']" ).click (
1235+ timeout = timeout
1236+ )
12261237
12271238 self ._loc_events .press ("Escape" )
1239+ return
12281240
12291241 def expect_choices (
12301242 self ,
0 commit comments