/
updateMetadata.ts
48 lines (40 loc) · 1.38 KB
/
updateMetadata.ts
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
import { validate } from './validate';
import type { ContentModelWithDataset, Definition } from 'roosterjs-content-model-types';
const EditingInfoDatasetName = 'editingInfo';
/**
* Update metadata of the given model
* @param model The model to update metadata to
* @param callback A callback function to update metadata
* @param definition @optional Metadata definition used for verify the metadata object
* @returns The metadata object if any, or null
*/
export function updateMetadata<T>(
model: ContentModelWithDataset<T>,
callback?: (metadata: T | null) => T | null,
definition?: Definition<T>
): T | null {
const metadataString = model.dataset[EditingInfoDatasetName];
let obj: T | null = null;
try {
obj = JSON.parse(metadataString) as T;
} catch {}
if (definition && !validate(obj, definition)) {
obj = null;
}
if (callback) {
obj = callback(obj);
if (!obj) {
delete model.dataset[EditingInfoDatasetName];
} else if (!definition || validate(obj, definition)) {
model.dataset[EditingInfoDatasetName] = JSON.stringify(obj);
}
}
return obj;
}
/**
* Check if the given model has metadata
* @param model The content model to check
*/
export function hasMetadata<T>(model: ContentModelWithDataset<T> | HTMLElement): boolean {
return !!model.dataset[EditingInfoDatasetName];
}