Debian Codegraph @

packages/notebook-extension/src/trusted.tsx

raw
1 import { ReactWidget } from '@jupyterlab/apputils';
2
3 import { Notebook, NotebookActions } from '@jupyterlab/notebook';
4
5 import { ITranslator } from '@jupyterlab/translation';
6
7 import React, { useEffect, useState } from 'react';
8
9 /**
10 * Check if a notebook is trusted
11 * @param notebook The notebook to check
12 * @returns true if the notebook is trusted, false otherwise
13 */
14 const isTrusted = (notebook: Notebook): boolean => {
15 const model = notebook.model;
16 if (!model) {
17 return false;
18 }
19 const cells = Array.from(model.cells);
20
21 const trusted = cells.reduce((accum, current) => {
22 if (current.trusted) {
23 return accum + 1;
24 } else {
25 return accum;
26 }
27 }, 0);
28
29 const total = cells.length;
30 return trusted === total;
31 };
32
33 /**
34 * A React component to display the Trusted badge in the menu bar.
35 * @param notebook The Notebook
36 * @param translator The Translation service
37 */
38 const TrustedButton = ({
39 notebook,
40 translator,
41 }: {
42 notebook: Notebook;
43 translator: ITranslator;
44 }): JSX.Element => {
45 const trans = translator.load('notebook');
46 const [trusted, setTrusted] = useState(isTrusted(notebook));
47
48 const checkTrust = () => {
49 const v = isTrusted(notebook);
50 setTrusted(v);
51 };
52
53 const trust = async () => {
54 await NotebookActions.trust(notebook, translator);
55 checkTrust();
56 };
57
58 useEffect(() => {
59 notebook.modelContentChanged.connect(checkTrust);
60 notebook.activeCellChanged.connect(checkTrust);
61 checkTrust();
62 return () => {
63 notebook.modelContentChanged.disconnect(checkTrust);
64 notebook.activeCellChanged.disconnect(checkTrust);
65 };
66 });
67
68 return (
69 <button
70 className={'jp-NotebookTrustedStatus'}
71 style={!trusted ? { cursor: 'pointer' } : { cursor: 'help' }}
72 onClick={() => !trusted && trust()}
73 title={
74 trusted
75 ? trans.__('JavaScript enabled for notebook display')
76 : trans.__('JavaScript disabled for notebook display')
77 }
78 >
79 {trusted ? trans.__('Trusted') : trans.__('Not Trusted')}
80 </button>
81 );
82 };
83
84 /**
85 * A namespace for TrustedComponent statics.
86 */
87 export namespace TrustedComponent {
88 /**
89 * Create a new TrustedComponent
90 *
91 * @param notebook The notebook
92 * @param translator The translator
93 */
94 export const create = ({
95 notebook,
96 translator,
97 }: {
98 notebook: Notebook;
99 translator: ITranslator;
100 }): ReactWidget => {
101 return ReactWidget.create(
102 <TrustedButton notebook={notebook} translator={translator} />
103 );
104 };
105 }