This repository was archived by the owner on Nov 3, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathimageContent.js
420 lines (388 loc) · 14 KB
/
imageContent.js
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
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
import { h, createRef, Fragment, Component } from 'preact';
import Resource from './utils/resource.js'
import Location from './utils/location.js'
import Client from './client.js'
import * as Matrix from "matrix-js-sdk"
import { onlineOrAlert } from "./utils/alerts.js"
import './styles/imageContent.css'
import { mscLocation, mscMediaFragment, populusHighlight } from "./constants.js"
export default class ImageContent extends Component {
static ImageStore = {}
componentDidMount() {
this.fetchImage()
}
async fetchImage () {
const theImage = new Resource(this.props.room)
if (!ImageContent.ImageStore[theImage.url]) {
ImageContent.ImageStore[theImage.url] = window.fetch(theImage.httpUrl)
.then(async response => {
const theClone = response.clone()
const contentLength = +response.headers.get('Content-Length')
const reader = response.body.getReader()
let accumulator = 0
while (true) {
const { done, value } = await reader.read()
if (done) { break }
accumulator = accumulator + value.length
this.props.setImageLoadingStatus(accumulator / contentLength)
}
const blob = await theClone.blob()
return URL.createObjectURL(blob)
})
.catch(this.catchFetchImageError)
} else { console.log(`found file for ${this.props.room.name} in store` ) }
ImageContent.ImageStore[theImage.url].then(url => this.props.resource.resolveFetch(url))
ImageContent.ImageStore[theImage.url].then(this.drawImage)
// TODO: this throws an error when the user exits the page before the media
// has been drawn. it should be caught, similarly for PDF fetching
}
drawImage = imageUrl => {
const theImage = new Image()
theImage.src = imageUrl
theImage.onload = _ => {
this.props.setContentDimensions(theImage.height, theImage.width)
const widthRatio = this.props.contentContainer.current.offsetWidth / theImage.width
if (widthRatio < 1) this.props.setZoom(_ => widthRatio)
this.setState({imageUrl})
}
}
hasSelection() { return !!this.state.selection }
createSelection = e => {
if (this.longPressTimeout) return
const initialOffsetX = e.offsetX
const initialOffsetY = e.offsetY
// Firefox doesn't keep the offsets of the pointer event around, for some
// reason, so we store them here.
this.longPressTimeout = setTimeout(_ => {
this.setState({
selection: new ImageAnnotation({
x: Math.round(initialOffsetX),
y: Math.round(initialOffsetY),
h:100,
w:100,
imageWidth: this.props.contentWidthPx,
imageHeight: this.props.contentHeightPx,
})
}, _ => document.dispatchEvent(new Event("selectionchange")))
}, 500)
}
handlePointerCancel = _ => {
clearTimeout(this.longPressTimeout)
delete this.longPressTimeout
}
clearSelection = _ => {
this.setState({
selection: null
}, _ => document.dispatchEvent(new Event("selectionchange")))
// XXX If the clear is the result of a two-finger zoom gesture, this
// prevents the second finger from triggering a new selection
this.longPressTimeout = setTimeout(_ => { })
}
generateLocation = _ => {
return {
[mscMediaFragment]: {
x: this.state.selection.x,
y: this.state.selection.y,
w: this.state.selection.w,
h: this.state.selection.h
},
[populusHighlight]: {
activityStatus: "pending",
creator: Client.client.getUserId()
}
}
}
get zoomMin () {
if (!this.props.contentWidthPx) return 0
return Math.min(
1,
this.props.contentContainer.current.offsetWidth / this.props.contentWidthPx,
this.props.contentContainer.current.offsetHeight / this.props.contentHeightPx
)
}
zoomMax = 10
commitRegion = _ => {
if (!onlineOrAlert()) return
const theDomain = Client.client.getDomain()
const theRoomState = this.props.room.getLiveTimeline().getState(Matrix.EventTimeline.FORWARDS)
const theLevels = theRoomState.getStateEvents(Matrix.EventType.RoomPowerLevels, "")
const locationData = this.generateLocation()
return Client.client.createRoom({
visibility: "private",
name: `selected region at ${this.state.selection.x},${this.state.selection.y}`,
power_level_content_override: {
users: Object.assign({}, theLevels.getContent().users, {
[Client.client.getUserId()]: 100
})
},
initial_state: [{
type: Matrix.EventType.RoomJoinRules,
state_key: "",
content: {join_rule: "public"}
},
{
type: Matrix.EventType.SpaceParent, // we indicate that the current room is the parent
content: { via: [theDomain], [mscLocation]: locationData },
state_key: this.props.room.roomId
}
]
}).then(roominfo => {
// set child event in pdfRoom State
this.clearSelection()
const childContent = { via: [theDomain], [mscLocation]: locationData }
// We focus on a new fake placeholder event to potentially insert the highlight immediately
const fakeEvent = new Matrix.MatrixEvent({
type: Matrix.EventType.SpaceChild,
origin_server_ts: new Date().getTime(),
room_id: this.props.room.roomId,
sender: Client.client.getUserId(),
state_key: roominfo.room_id,
content: childContent
})
Client.client.sendStateEvent(this.props.room.roomId, Matrix.EventType.SpaceChild, childContent, roominfo.room_id)
this.props.setFocus(new Location(fakeEvent))
this.props.showChat()
})
}
getAnnotations() {
return this.props.filteredAnnotationContents.map(loc => {
return new ImageAnnotation({
location: loc,
// we pass in focus so that it will be recalculated with renders
focused: loc.getChild() === this.props.focus?.getChild(),
imageWidth: this.props.contentWidthPx,
imageHeight: this.props.contentHeightPx,
setFocus: this.props.setFocus
})
})
}
render(props, state) {
if (!props.contentWidthPx) return
return <div id="image-view-wrapper">
<div
data-image-selecting={!!state.selection}
id="image-view" >
<img src={state.imageUrl} />
<ImageOverlay
focus={props.focus}
handlePointerCancel={this.handlePointerCancel}
handlePointerDown={state.selection ? this.clearSelection : this.createSelection}
contentWidthPx={props.contentWidthPx}
contentHeightPx={props.contentHeightPx}
>{this.state.selection
? this.state.selection
: this.getAnnotations()
}
</ImageOverlay>
</div>
</div>
}
}
// XXX We don't use a component here since this should control two different
// <rect>s that need to appear in different places
class ImageAnnotation {
constructor({x,y,h,w, location, focused, setFocus, imageHeight, imageWidth}) {
const rect = location?.getMediaRect()
this.x = rect?.x || x
this.y = rect?.y || y
this.h = rect?.height || h
this.w = rect?.width || w
this.location = location
this.imageHeight = imageHeight
this.selection = !location
this.setFocus = setFocus
this.imageWidth = imageWidth
this.focused = focused
this.maskRef = createRef()
this.rectRef = createRef()
this.rectResizeHRef = createRef()
this.rectResizeWRef = createRef()
this.key = Date.now()
}
focusAnnotation = e => {
e.stopPropagation() //prevent a secondary seek
this.setFocus(this.location)
}
startDrag = e => {
e.stopPropagation()
if (this.initialPointer) return
this.initialX = this.x
this.initialY = this.y
this.initialOffsetX = e.offsetX
this.initialOffsetY = e.offsetY
this.initialPointer = e.pointerId
this.rectRef.current.setPointerCapture(e.pointerId)
this.rectRef.current.addEventListener('pointermove', this.handleDrag)
this.rectRef.current.addEventListener('pointerup', e => {
if (e.pointerId !== this.initialPointer) return
delete this.initialX
delete this.initialY
delete this.initialPointer
delete this.initialOffsetX
delete this.initialOffsetY
this.rectRef.current?.releasePointerCapture(e.pointerId)
this.rectRef.current?.removeEventListener('pointermove', this.handleDrag)
})
}
handleDrag = e => {
e.preventDefault()
if (e.pointerId !== this.initialPointer) return
this.x = Math.round(Math.min(Math.max(0, this.initialX + (e.offsetX- this.initialOffsetX )), this.imageWidth - this.w))
this.y = Math.round(Math.min(Math.max(0, this.initialY + (e.offsetY - this.initialOffsetY)), this.imageHeight - this.h))
requestAnimationFrame(this.updateSizes)
}
updateSizes = _ => {
this.rectRef.current.setAttribute("x", this.x)
this.rectRef.current.setAttribute("y", this.y)
this.rectRef.current.setAttribute("width", this.w - 20)
this.rectRef.current.setAttribute("height", this.h - 20)
this.maskRef.current.setAttribute("x", this.x)
this.maskRef.current.setAttribute("y", this.y)
this.maskRef.current.setAttribute("width", this.w)
this.maskRef.current.setAttribute("height", this.h)
this.rectResizeWRef.current.setAttribute("y", this.y)
this.rectResizeWRef.current.setAttribute("x", this.x + this.w - 20)
this.rectResizeWRef.current.setAttribute("height", this.h - 20)
this.rectResizeHRef.current.setAttribute("x", this.x)
this.rectResizeHRef.current.setAttribute("width", this.w)
this.rectResizeHRef.current.setAttribute("y", this.y + this.h - 20)
}
startResizeW = e => {
e.stopPropagation()
if (this.initialPointer) return
this.rectResizeWRef.current.setPointerCapture(e.pointerId)
this.initialWidth = this.w
this.initialOffsetX = e.offsetX
this.initialPointer = e.pointerId
this.rectResizeWRef.current.addEventListener('pointermove', this.handleResizeW)
this.rectResizeWRef.current.addEventListener('pointerup', e => {
if (e.pointerId !== this.initialPointer) return
delete this.initialPointer
delete this.initialWidth
delete this.initialOffsetX
this.rectResizeWRef.current?.releasePointerCapture(e.pointerId)
this.rectResizeWRef.current?.removeEventListener('pointermove', this.handleResizeW)
})
}
startResizeH = e => {
e.stopPropagation()
if (this.initialPointer) return
this.rectResizeHRef.current.setPointerCapture(e.pointerId)
this.initialHeight = this.h
this.initialOffsetY = e.offsetY
this.initialPointer = e.pointerId
this.rectResizeHRef.current.addEventListener('pointermove', this.handleResizeH)
this.rectResizeHRef.current.addEventListener('pointerup', _ => {
if (e.pointerId !== this.initialPointer) return
delete this.initialHeight
delete this.initialOffsetY
delete this.initialPointer
this.rectResizeHRef.current?.releasePointerCapture(e.pointerId)
this.rectResizeHRef.current?.removeEventListener('pointermove', this.handleResizeH)
})
}
handleResizeW = e => {
e.preventDefault()
if (e.pointerId !== this.initialPointer) return
//the 40px minimum here accomodates the handles
this.w = Math.round(Math.min(this.imageWidth - this.x, Math.max(40, this.initialWidth + (e.offsetX - this.initialOffsetX))))
this.updateSizes()
}
handleResizeH = e => {
e.preventDefault()
if (e.pointerId !== this.initialPointer) return
//the 40px minimum here accomodates the handles
this.h = Math.round(Math.min(this.imageHeight - this.y, Math.max(40, this.initialHeight + (e.offsetY - this.initialOffsetY))))
this.updateSizes()
}
}
class ImageOverlay extends Component {
getMasks = _ => this.props.children?.map(this.toMask)
componentDidUpdate(prevProps) {
if (prevProps.focus?.getChild() !== this.props.focus?.getChild()) {
this.focusedRect?.current?.scrollIntoView({block:"center", inline:"center"})
}
}
toMask = child => <rect
key={child.key}
ref={child.maskRef}
x={child.x}
y={child.y}
width={child.w}
height={child.h}
/>
getRects = _ => this.props.children?.map(this.toRect)
toRect = child => {
if (child.focused) this.focusedRect = child.rectRef
return <rect
key={child.key + 1}
ref={child.rectRef}
mask="url(#mask)"
onpointerdown={child.focusAnnotation}
class="image-annotation-rect"
x={child.x}
y={child.y}
width={child.w}
height={child.h}
data-annotation-focused={child.focused}
/>
}
toSelection = child => <Fragment>
<rect
key={child.key + 2}
ref={child.rectRef}
mask="url(#mask)"
class="image-annotation-rect-drag"
x={child.x}
y={child.y}
onpointerdown={child.startDrag}
width={child.w - 20}
height={child.h - 20}
/>
<rect
key={child.key + 3}
ref={child.rectResizeWRef}
mask="url(#mask)"
class="image-annotation-rect-resize-w"
x={child.x + child.w - 20}
y={child.y}
onpointerdown={child.startResizeW}
width={20}
height={child.h - 20}
/>
<rect
key={child.key + 4}
ref={child.rectResizeHRef}
mask="url(#mask)"
class="image-annotation-rect-resize-h"
x={child.x}
y={child.y + child.h - 20}
onpointerdown={child.startResizeH}
width={child.w}
height={20}
/>
</Fragment>
render (props, state) {
const outerPath = `M0 0 h${props.contentWidthPx} v${props.contentHeightPx} h-${props.contentWidthPx}z`
return <svg
onPointerCancel={props.handlePointerCancel}
onPointerUp={props.handlePointerCancel}
onPointerDown={props.handlePointerDown}
id="image-overlay">
<defs>
<mask id="mask">
<path fill="white" d={outerPath}/>
{ props.children?.selection
? this.toMask(props.children)
: this.getMasks()
}
</mask>
</defs>
<path mask="url(#mask)" fill="black" d={outerPath}/>
{ props.children?.selection
? this.toSelection(props.children)
: this.getRects()
}
</svg>
}
}