Debian Codegraph @

pkg/lib/cockpit-components-file-autocomplete.tsx

raw
1 /*
2 * Copyright (C) 2017 Red Hat, Inc.
3 * SPDX-License-Identifier: LGPL-2.1-or-later
4 */
5
6 import cockpit from "cockpit";
7 import React from "react";
8 import { debounce } from 'throttle-debounce';
9 import { TypeaheadSelect } from "cockpit-components-typeahead-select";
10
11 const _ = cockpit.gettext;
12
13 interface FileEntry {
14 type: "file" | "directory" | "link" | "special";
15 path: string;
16 }
17
18 interface FileAutoCompleteProps {
19 id?: string;
20 placeholder?: string;
21 superuser?: cockpit.SuperuserMode;
22 isOptionCreatable: boolean;
23 onlyDirectories: boolean;
24 onChange: (value: string, error?: string | null) => void;
25 value?: string;
26 }
27
28 interface FileAutoCompleteState {
29 directory: string;
30 displayFiles: FileEntry[];
31 value: string | null;
32 error?: string | null;
33 }
34
35 export class FileAutoComplete extends React.Component<FileAutoCompleteProps, FileAutoCompleteState> {
36 static defaultProps: Partial<FileAutoCompleteProps> = {
37 isOptionCreatable: false,
38 onlyDirectories: false,
39 onChange: () => '',
40 };
41
42 allowFilesUpdate: boolean;
43 debouncedChange: (value: string) => void;
44
45 constructor(props: FileAutoCompleteProps) {
46 super(props);
47 this.state = {
48 directory: '', // The current directory we list files/dirs from
49 displayFiles: [],
50 value: this.props.value || null,
51 };
52
53 this.allowFilesUpdate = true;
54 this.clearSelection = this.clearSelection.bind(this);
55
56 this.debouncedChange = debounce(300, this.onPathChange);
57 }
58
59 onPathChange = (value: string) => {
60 if (!value) {
61 this.clearSelection();
62 return;
63 }
64
65 const cb = (dirPath: string) => this.updateFiles(dirPath == '' ? '/' : dirPath);
66
67 let path = value;
68 if (value.lastIndexOf('/') == value.length - 1)
69 path = value.slice(0, value.length - 1);
70
71 const match = this.state.displayFiles
72 .find(entry => (entry.type == 'directory' && entry.path == path + '/') || (entry.type == 'file' && entry.path == path));
73
74 if (match) {
75 // If match file path is a prefix of another file, do not update current directory,
76 // since we cannot tell file/directory user wants to select
77 // https://bugzilla.redhat.com/show_bug.cgi?id=2097662
78 const isPrefix = this.state.displayFiles.filter(entry => entry.path.startsWith(value)).length > 1;
79 // If the inserted string corresponds to a directory listed in the results
80 // update the current directory and refetch results
81 if (match.type == 'directory' && !isPrefix)
82 cb(match.path);
83 else
84 this.setState({ value: match.path });
85 } else {
86 // If the inserted string's parent directory is not matching the `directory`
87 // in the state object we need to update the parent directory and recreate the displayFiles
88 const parentDir = value.slice(0, value.lastIndexOf('/'));
89
90 if (parentDir + '/' != this.state.directory) {
91 return this.updateFiles(parentDir + '/');
92 }
93 }
94 };
95
96 componentDidMount() {
97 this.onPathChange(this.state.value || '');
98 }
99
100 componentWillUnmount() {
101 this.allowFilesUpdate = false;
102 }
103
104 updateFiles(path: string) {
105 if (this.state.directory == path)
106 return;
107
108 const channel = cockpit.channel({
109 payload: "fslist1",
110 path,
111 superuser: this.props.superuser,
112 watch: false,
113 });
114 const results: FileEntry[] = [];
115
116 channel.addEventListener("ready", () => {
117 this.finishUpdate(results, null, path);
118 });
119
120 channel.addEventListener("close", (_ev, data) => {
121 this.finishUpdate(results, data.message as string | null, path);
122 });
123
124 channel.addEventListener("message", (_ev, data) => {
125 const item = JSON.parse(data);
126 if (item && item.path && item.event == 'present' &&
127 (!this.props.onlyDirectories || item.type == 'directory')) {
128 item.path = item.path + (item.type == 'directory' ? '/' : '');
129 results.push(item);
130 }
131 });
132 }
133
134 finishUpdate(results: FileEntry[], error: string | null, directory: string) {
135 if (!this.allowFilesUpdate)
136 return;
137 results = results.sort((a, b) => a.path.localeCompare(b.path));
138
139 const listItems: FileEntry[] = results.map(file => ({
140 type: file.type,
141 path: (directory == '' ? '/' : directory) + file.path
142 }));
143
144 if (directory) {
145 listItems.unshift({
146 type: "directory",
147 path: directory
148 });
149 }
150
151 if (error || !this.state.value)
152 this.props.onChange('', error);
153
154 if (!error)
155 this.setState({ displayFiles: listItems, directory });
156 this.setState({
157 error,
158 });
159 }
160
161 clearSelection() {
162 this.updateFiles("/");
163 this.setState({ value: null });
164 this.props.onChange('', null);
165 }
166
167 render() {
168 const placeholder = this.props.placeholder || _("Path to file");
169
170 const selectOptions = this.state.displayFiles
171 .map(option => ({ value: option.path, content: option.path, className: option.type }));
172
173 return (
174 <TypeaheadSelect toggleProps={{ id: this.props.id }}
175 isScrollable
176 onInputChange={this.debouncedChange}
177 placeholder={placeholder}
178 noOptionsAvailableMessage={this.state.error || _("No such file or directory")}
179 noOptionsFoundMessage={this.state.error || _("No such file or directory")}
180 onToggle={isOpen => {
181 // Try to list again when
182 // opening. Calling onPathChange here
183 // usually does nothing, except when
184 // there was an error earlier.
185 if (isOpen)
186 this.onPathChange(this.state.value || '');
187 }}
188 selected={this.state.value}
189 selectedIsTrusted
190 onSelect={(_, value) => {
191 const path = String(value);
192 this.setState({ value: path });
193 this.onPathChange(path);
194 this.props.onChange(path, null);
195 }}
196 onClearSelection={this.clearSelection}
197 isCreatable={this.props.isOptionCreatable}
198 createOptionMessage={val => cockpit.format(_("Create $0"), val)}
199 selectOptions={selectOptions} />
200 );
201 }
202 }