-
Notifications
You must be signed in to change notification settings - Fork 5k
/
trusted.tsx
107 lines (94 loc) · 2.52 KB
/
trusted.tsx
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
import { ReactWidget } from '@jupyterlab/apputils';
import { Notebook, NotebookActions } from '@jupyterlab/notebook';
import { ITranslator } from '@jupyterlab/translation';
import { toArray } from '@lumino/algorithm';
import React, { useEffect, useState } from 'react';
/**
* Check if a notebook is trusted
* @param notebook The notebook to check
* @returns true if the notebook is trusted, false otherwise
*/
const isTrusted = (notebook: Notebook): boolean => {
const model = notebook.model;
if (!model) {
return false;
}
const cells = toArray(model.cells);
const trusted = cells.reduce((accum, current) => {
if (current.trusted) {
return accum + 1;
} else {
return accum;
}
}, 0);
const total = cells.length;
return trusted === total;
};
/**
* A React component to display the Trusted badge in the menu bar.
* @param notebook The Notebook
* @param translator The Translation service
*/
const TrustedButton = ({
notebook,
translator
}: {
notebook: Notebook;
translator: ITranslator;
}): JSX.Element => {
const trans = translator.load('notebook');
const [trusted, setTrusted] = useState(isTrusted(notebook));
const checkTrust = () => {
const v = isTrusted(notebook);
setTrusted(v);
};
const trust = async () => {
await NotebookActions.trust(notebook, translator);
checkTrust();
};
useEffect(() => {
notebook.modelContentChanged.connect(checkTrust);
notebook.activeCellChanged.connect(checkTrust);
checkTrust();
return () => {
notebook.modelContentChanged.disconnect(checkTrust);
notebook.activeCellChanged.disconnect(checkTrust);
};
});
return (
<button
className={'jp-NotebookTrustedStatus'}
style={!trusted ? { cursor: 'pointer' } : { cursor: 'help' }}
onClick={() => !trusted && trust()}
title={
trusted
? trans.__('JavaScript enabled for notebook display')
: trans.__('JavaScript disabled for notebook display')
}
>
{trusted ? trans.__('Trusted') : trans.__('Not Trusted')}
</button>
);
};
/**
* A namespace for TrustedComponent statics.
*/
export namespace TrustedComponent {
/**
* Create a new TrustedComponent
*
* @param notebook The notebook
* @param translator The translator
*/
export const create = ({
notebook,
translator
}: {
notebook: Notebook;
translator: ITranslator;
}): ReactWidget => {
return ReactWidget.create(
<TrustedButton notebook={notebook} translator={translator} />
);
};
}