luxiaotao1123
2024-06-21 569d2b6bc754b037ade5b4205a4d1cdb8339b26b
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
import React, { useCallback, useEffect, useState } from 'react';
import { Upload, Tooltip, Popover, Modal, Progress, Spin, Result } from 'antd';
import * as AntdIcons from '@ant-design/icons';
import { useIntl } from '@umijs/max';
import './style.less';
 
const allIcons: { [key: string]: any } = AntdIcons;
 
const { Dragger } = Upload;
interface AntdIconClassifier {
  load: () => void;
  predict: (imgEl: HTMLImageElement) => void;
}
declare global {
  interface Window {
    antdIconClassifier: AntdIconClassifier;
  }
}
 
interface PicSearcherState {
  loading: boolean;
  modalOpen: boolean;
  popoverVisible: boolean;
  icons: iconObject[];
  fileList: any[];
  error: boolean;
  modelLoaded: boolean;
}
 
interface iconObject {
  type: string;
  score: number;
}
 
const PicSearcher: React.FC = () => {
  const intl = useIntl();
  const {formatMessage} = intl;
  const [state, setState] = useState<PicSearcherState>({
    loading: false,
    modalOpen: false,
    popoverVisible: false,
    icons: [],
    fileList: [],
    error: false,
    modelLoaded: false,
  });
  const predict = (imgEl: HTMLImageElement) => {
    try {
      let icons: any[] = window.antdIconClassifier.predict(imgEl);
      if (gtag && icons.length) {
        gtag('event', 'icon', {
          event_category: 'search-by-image',
          event_label: icons[0].className,
        });
      }
      icons = icons.map(i => ({ score: i.score, type: i.className.replace(/\s/g, '-') }));
      setState(prev => ({ ...prev, loading: false, error: false, icons }));
    } catch {
      setState(prev => ({ ...prev, loading: false, error: true }));
    }
  };
  // eslint-disable-next-line class-methods-use-this
  const toImage = (url: string) =>
    new Promise(resolve => {
      const img = new Image();
      img.setAttribute('crossOrigin', 'anonymous');
      img.src = url;
      img.onload = () => {
        resolve(img);
      };
    });
 
  const uploadFile = useCallback((file: File) => {
    setState(prev => ({ ...prev, loading: true }));
    const reader = new FileReader();
    reader.onload = () => {
      toImage(reader.result as string).then(predict);
      setState(prev => ({
        ...prev,
        fileList: [{ uid: 1, name: file.name, status: 'done', url: reader.result }],
      }));
    };
    reader.readAsDataURL(file);
  }, []);
 
  const onPaste = useCallback((event: ClipboardEvent) => {
    const items = event.clipboardData && event.clipboardData.items;
    let file = null;
    if (items && items.length) {
      for (let i = 0; i < items.length; i++) {
        if (items[i].type.includes('image')) {
          file = items[i].getAsFile();
          break;
        }
      }
    }
    if (file) {
      uploadFile(file);
    }
  }, []);
  const toggleModal = useCallback(() => {
    setState(prev => ({
      ...prev,
      modalOpen: !prev.modalOpen,
      popoverVisible: false,
      fileList: [],
      icons: [],
    }));
    if (!localStorage.getItem('disableIconTip')) {
      localStorage.setItem('disableIconTip', 'true');
    }
  }, []);
 
  useEffect(() => {
    const script = document.createElement('script');
    script.onload = async () => {
      await window.antdIconClassifier.load();
      setState(prev => ({ ...prev, modelLoaded: true }));
      document.addEventListener('paste', onPaste);
    };
    script.src = 'https://cdn.jsdelivr.net/gh/lewis617/antd-icon-classifier@0.0/dist/main.js';
    document.head.appendChild(script);
    setState(prev => ({ ...prev, popoverVisible: !localStorage.getItem('disableIconTip') }));
    return () => {
      document.removeEventListener('paste', onPaste);
    };
  }, []);
 
  return (
    <div className="iconPicSearcher">
      <Popover
        content={formatMessage({id: 'app.docs.components.icon.pic-searcher.intro'})}
        open={state.popoverVisible}
      >
        <AntdIcons.CameraOutlined className="icon-pic-btn" onClick={toggleModal} />
      </Popover>
      <Modal
        title={intl.formatMessage({
          id: 'app.docs.components.icon.pic-searcher.title',
          defaultMessage: '信息',
        })}
        open={state.modalOpen}
        onCancel={toggleModal}
        footer={null}
      >
        {state.modelLoaded || (
          <Spin
            spinning={!state.modelLoaded}
            tip={formatMessage({
              id: 'app.docs.components.icon.pic-searcher.modelloading',
 
            })}
          >
            <div style={{ height: 100 }} />
          </Spin>
        )}
        {state.modelLoaded && (
          <Dragger
            accept="image/jpeg, image/png"
            listType="picture"
            customRequest={o => uploadFile(o.file as File)}
            fileList={state.fileList}
            showUploadList={{ showPreviewIcon: false, showRemoveIcon: false }}
          >
            <p className="ant-upload-drag-icon">
              <AntdIcons.InboxOutlined />
            </p>
            <p className="ant-upload-text">
              {formatMessage({id: 'app.docs.components.icon.pic-searcher.upload-text'})}
            </p>
            <p className="ant-upload-hint">
              {formatMessage({id: 'app.docs.components.icon.pic-searcher.upload-hint'})}
            </p>
          </Dragger>
        )}
        <Spin
          spinning={state.loading}
          tip={formatMessage({id: 'app.docs.components.icon.pic-searcher.matching'})}
        >
          <div className="icon-pic-search-result">
            {state.icons.length > 0 && (
              <div className="result-tip">
                {formatMessage({id: 'app.docs.components.icon.pic-searcher.result-tip'})}
              </div>
            )}
            <table>
              {state.icons.length > 0 && (
                <thead>
                  <tr>
                    <th className="col-icon">
                      {formatMessage({id: 'app.docs.components.icon.pic-searcher.th-icon'})}
                    </th>
                    <th>{formatMessage({id: 'app.docs.components.icon.pic-searcher.th-score'})}</th>
                  </tr>
                </thead>
              )}
              <tbody>
                {state.icons.map(icon => {
                  const { type } = icon;
                  const iconName = `${type
                    .split('-')
                    .map(str => `${str[0].toUpperCase()}${str.slice(1)}`)
                    .join('')}Outlined`;
                  return (
                    <tr key={iconName}>
                      <td className="col-icon">
                          <Tooltip title={icon.type} placement="right">
                            {React.createElement(allIcons[iconName])}
                          </Tooltip>
                      </td>
                      <td>
                        <Progress percent={Math.ceil(icon.score * 100)} />
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
            {state.error && (
              <Result
                status="500"
                title="503"
                subTitle={formatMessage({id: 'app.docs.components.icon.pic-searcher.server-error'})}
              />
            )}
          </div>
        </Spin>
      </Modal>
    </div>
  );
};
 
export default PicSearcher;