aboutsummaryrefslogtreecommitdiff
path: root/src/client/views/InkTranscription.tsx
blob: 0ac1770cc60a873ab0757c65d741632ec8514ca6 (plain)
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
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
import * as iink from 'iink-js';
import { action, observable } from 'mobx';
import * as React from 'react';
import { Doc, DocListCast, HeightSym, WidthSym } from '../../fields/Doc';
import { InkData, InkField } from "../../fields/InkField";
import { Cast, DateCast, NumCast } from '../../fields/Types';
import { aggregateBounds } from '../../Utils';
import { DocumentType } from "../documents/DocumentTypes";
import { DocumentManager } from "../util/DocumentManager";
import { CollectionFreeFormView } from './collections/collectionFreeForm';
import { InkingStroke } from './InkingStroke';
import './InkTranscription.scss';


export class InkTranscription extends React.Component {
    static Instance: InkTranscription;

    @observable _mathRegister: any;
    @observable _mathRef: any;
    @observable _textRegister: any;
    @observable _textRef: any;
    private lastJiix: any;
    private currGroup?: Doc;

    constructor(props: Readonly<{}>) {
        super(props);

        InkTranscription.Instance = this;
    }

    componentWillUnmount() {
        this._mathRef.removeEventListener('exported', (e: any) => this.exportInk(e, this._mathRef));
        this._textRef.removeEventListener('exported', (e: any) => this.exportInk(e, this._textRef));
    }

    @action
    setMathRef = (r: any) => {
        if (!this._mathRegister) {
            this._mathRegister = r ? iink.register(r, {
                recognitionParams: {
                    type: 'MATH',
                    protocol: 'WEBSOCKET',
                    server: {
                        host: 'cloud.myscript.com',
                        applicationKey: '7277ec34-0c2e-4ee1-9757-ccb657e3f89f',
                        hmacKey: 'f5cb18f2-1f95-4ddb-96ac-3f7c888dffc1',
                        websocket: {
                            pingEnabled: false,
                            autoReconnect: true
                        }
                    },
                    iink: {
                        math: {
                            mimeTypes: ['application/x-latex', 'application/vnd.myscript.jiix']
                        },
                        export: {
                            jiix: {
                                strokes: true
                            }
                        }
                    }
                }
            }) : null;
        }

        r.addEventListener('exported', (e: any) => this.exportInk(e, this._mathRef));

        return this._mathRef = r;
    }

    @action
    setTextRef = (r: any) => {
        if (!this._textRegister) {
            this._textRegister = r ? iink.register(r, {
                recognitionParams: {
                    type: 'TEXT',
                    protocol: 'WEBSOCKET',
                    server: {
                        host: 'cloud.myscript.com',
                        applicationKey: '7277ec34-0c2e-4ee1-9757-ccb657e3f89f',
                        hmacKey: 'f5cb18f2-1f95-4ddb-96ac-3f7c888dffc1',
                        websocket: {
                            pingEnabled: false,
                            autoReconnect: true
                        }
                    },
                    iink: {
                        text: {
                            mimeTypes: ['text/plain']
                        },
                        export: {
                            jiix: {
                                strokes: true
                            }
                        }
                    }
                }
            }) : null;
        }

        r.addEventListener('exported', (e: any) => this.exportInk(e, this._textRef));

        return this._textRef = r;
    }

    transcribeInk = (groupDoc: Doc | undefined, inkDocs: Doc[], math: boolean, ffView?: CollectionFreeFormView) => {
        if (!groupDoc) return;
        const validInks = inkDocs.filter(s => s.type === DocumentType.INK);

        const strokes: InkData[] = [];
        const times: number[] = [];
        validInks.filter(i => Cast(i.data, InkField)).forEach(i => {
            const d = Cast(i.data, InkField, null);
            const inkStroke = DocumentManager.Instance.getDocumentView(i)?.ComponentView as InkingStroke;
            strokes.push(d.inkData.map(pd => (inkStroke.ptToScreen({ X: pd.X, Y: pd.Y }))));
            times.push(DateCast(i.creationDate).getDate().getTime());
        });

        this.currGroup = groupDoc;

        const pointerData = { "events": strokes.map((stroke, i) => this.inkJSON(stroke, times[i])) };
        const processGestures = false;

        if (math) {
            this._mathRef.editor.pointerEvents(pointerData, processGestures);
        }
        else {
            this._textRef.editor.pointerEvents(pointerData, processGestures);
        }
    }

    inkJSON = (stroke: InkData, time: number) => {
        return {
            "pointerType": "PEN",
            "pointerId": 1,
            "x": stroke.map(point => point.X),
            "y": stroke.map(point => point.Y),
            "t": new Array(stroke.length).fill(time),
            "p": new Array(stroke.length).fill(1.0)
        };
    }

    mmToPixel = (mm: number) => {
        return ((96 * mm) / 25.4);
    }

    calcBounds = (coords: any) => {
        // find max and min x values and subtract
        const max = Math.max(...coords);
        const min = Math.min(...coords);
        return max - min;
    }

    subgroupsTranscriptions = (wordInkDocMap: Map<string, Doc[]>) => {
        // loop through the words in wordInkDocMap
        // for each word, get the inkDocs

        // iterate through the keys of wordInkDocMap
        wordInkDocMap.forEach(async (inkDocs: Doc[], word: string) => {
            const selected = inkDocs.slice();
            if (!selected) {
                return;
            }
            // TODO: nda - probably have to cast this to an actual Doc
            const ctx = await Cast(selected[0].context, Doc);
            if (!ctx) {
                return;
            }
            const docView: CollectionFreeFormView = DocumentManager.Instance.getDocumentView(ctx)?.ComponentView as CollectionFreeFormView;

            if (!docView) return;
            const marqViewRef = docView._marqueeViewRef.current;
            if (!marqViewRef) return;
            //  loop through selected an get the bound
            const bounds: { x: number, y: number, width?: number, height?: number }[] = []

            selected.map(action(d => {
                const x = NumCast(d.x);
                const y = NumCast(d.y);
                const width = d[WidthSym]();
                const height = d[HeightSym]();
                bounds.push({ x, y, width, height });
            }))

            const aggregBounds = aggregateBounds(bounds, 0, 0);

            if (marqViewRef) {
                marqViewRef._downX = aggregBounds.x;
                marqViewRef._downY = aggregBounds.y;
                marqViewRef._lastX = aggregBounds.r;
                marqViewRef._lastY = aggregBounds.b;
            }

            // set the vals for bounds in marqueeView

            selected.map(action(d => {
                const dx = NumCast(d.x);
                const dy = NumCast(d.y);
                delete d.x;
                delete d.y;
                delete d.activeFrame;
                delete d._timecodeToShow;  // bcz: this should be automatic somehow.. along with any other properties that were logically associated with the original collection
                delete d._timecodeToHide;  // bcz: this should be automatic somehow.. along with any other properties that were logically associated with the original collection
                // calculate pos based on bounds
                if (marqViewRef?.Bounds) {
                    d.x = dx - marqViewRef.Bounds.left - marqViewRef.Bounds.width / 2;
                    d.y = dy - marqViewRef.Bounds.top - marqViewRef.Bounds.height / 2;
                }
                return d;
            }));

            docView.props.removeDocument?.(selected);
            const newCollection = marqViewRef?.getCollection(selected, undefined, true);
            if (newCollection) {
                newCollection.height = newCollection[HeightSym]();
                newCollection.width = newCollection[WidthSym]();
                newCollection.title = word;
            }
            // nda - bug: when deleting a stroke before leaving writing mode, delete the stroke from unprocessed ink docs
            newCollection && docView.props.addDocument?.(newCollection);
        });
    }

    exportInk = (e: any, ref: any) => {
        const exports = e.detail.exports;
        if (exports) {
            if (exports['application/x-latex']) {
                const latex = exports['application/x-latex'];
                if (this.currGroup) {
                    this.currGroup.text = latex;
                    this.currGroup.title = latex;
                }

                ref.editor.clear();
            }
            else if (exports['text/plain']) {
                if (exports['application/vnd.myscript.jiix']) {
                    this.lastJiix = JSON.parse(exports['application/vnd.myscript.jiix']);
                    // map timestamp to strokes
                    const timestampWord = new Map<number, string>();
                    this.lastJiix.words.map((word: any) => {
                        if (word.items) {
                            word.items.forEach((i: { id: string, timestamp: string, X: Array<number>, Y: Array<number>, F: Array<number> }) => {
                                const ms = Date.parse(i.timestamp);
                                timestampWord.set(ms, word.label);
                            })
                        }
                    })

                    const wordInkDocMap = new Map<string, Doc[]>();
                    if (this.currGroup) {
                        const docList = DocListCast(this.currGroup.data)
                        docList.forEach((inkDoc: Doc) => {
                            // just having the times match up and be a unique value (actual timestamp doesn't matter)
                            const ms = DateCast(inkDoc.creationDate).getDate().getTime() + 14400000;
                            const word = timestampWord.get(ms);
                            if (!word) {
                                return;
                            }
                            const entry = wordInkDocMap.get(word);
                            if (entry) {
                                entry.push(inkDoc);
                                wordInkDocMap.set(word, entry);
                            } else {
                                const newEntry = [inkDoc];
                                wordInkDocMap.set(word, newEntry);
                            }
                        });
                        if (this.lastJiix.words.length > 1) this.subgroupsTranscriptions(wordInkDocMap);
                    }
                }
                const text = exports['text/plain'];

                if (this.currGroup) {
                    this.currGroup.transcription = text;
                    this.currGroup.title = text.split("\n")[0];
                }

                ref.editor.clear();
            }
        }
    }

    render() {
        return (
            <div className="ink-transcription">
                <div className='math-editor'
                    ref={this.setMathRef}
                    touch-action="none">
                </div>
                <div className='text-editor'
                    ref={this.setTextRef}
                    touch-action="none">
                </div>
            </div>
        )
    }
}