-
Notifications
You must be signed in to change notification settings - Fork 0
/
RdfEditor.js
120 lines (96 loc) · 2.49 KB
/
RdfEditor.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
/* global CustomEvent */
import prettyFormats from '@rdfjs/formats/pretty.js'
import rdf from 'rdf-ext'
import { Readable } from 'readable-stream'
import decode from 'stream-chunks/decode.js'
import { hasChangedDataset } from './hasChanged.js'
import BaseEditor from './src/BaseEditor.js'
import { turtle } from './src/lang-turtle.js'
class RdfEditor extends BaseEditor {
static get properties () {
return {
base: {
type: Object
},
dataset: {
type: Object,
hasChanged: hasChangedDataset
},
factory: {
type: Object
},
mediaType: {
type: String
},
prefixes: {
type: Object
}
}
}
constructor () {
super({ plugins: [turtle()] })
this._dataset = null
this._rdf = rdf.clone()
this._rdf.formats.import(prettyFormats)
this.prefixes = new Map()
}
get dataset () {
return this._dataset
}
set dataset (dataset) {
const oldValue = this._dataset
this._dataset = dataset
this.requestUpdate('dataset', oldValue)
}
firstUpdated () {
super.firstUpdated()
this._emitChange()
}
update (changedProperties) {
if (changedProperties.has('base')) {
this._serialize()
} else if (changedProperties.has('dataset')) {
this._serialize()
} else if (changedProperties.has('mediaType')) {
this._serialize()
} else if (changedProperties.has('prefixes')) {
this._serialize()
}
super.update(changedProperties)
}
async _emitChange () {
await this._parse()
const options = {
detail: {
dataset: this.dataset,
error: this.status.error,
value: this.value
}
}
this.dispatchEvent(new CustomEvent('change', options))
}
async _parse () {
try {
this._dataset = await rdf.io.dataset.fromText(this.mediaType, this.value)
this.status = { message: `${this._dataset.size} triples` }
} catch (error) {
this._dataset = null
this.status = { error }
}
this.editor.dispatch()
}
async _serialize () {
if (!this.editor) {
return
}
const dataset = this.dataset ? [...this.dataset] : []
const stream = Readable.from(dataset)
const output = this._rdf.formats.serializers.import(this.mediaType, stream, { baseIRI: this.base })
for (const [prefix, namespace] of this.prefixes) {
stream.emit('prefix', prefix, namespace)
}
this._value = await decode(output)
this._updateValue()
}
}
export default RdfEditor