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 let total = 0;
21 let trusted = 0;
22
23 for (const currentCell of cells) {
24 if (currentCell.type !== 'code') {
25 continue;
26 }
27 total++;
28 if (currentCell.trusted) {
29 trusted++;
30 }
31 }
32
33 return trusted === total;
34 };
35
36 /**
37 * A React component to display the Trusted badge in the menu bar.
38 * @param notebook The Notebook
39 * @param translator The Translation service
40 */
41 const TrustedButton = ({
42 notebook,
43 translator,
44 }: {
45 notebook: Notebook;
46 translator: ITranslator;
47 }): JSX.Element => {
48 const trans = translator.load('notebook');
49 const [trusted, setTrusted] = useState(isTrusted(notebook));
50
51 const checkTrust = () => {
52 const v = isTrusted(notebook);
53 setTrusted(v);
54 };
55
56 const trust = async () => {
57 await NotebookActions.trust(notebook, translator);
58 checkTrust();
59 };
60
61 useEffect(() => {
62 notebook.modelContentChanged.connect(checkTrust);
63 notebook.activeCellChanged.connect(checkTrust);
64 checkTrust();
65 return () => {
66 notebook.modelContentChanged.disconnect(checkTrust);
67 notebook.activeCellChanged.disconnect(checkTrust);
68 };
69 });
70
71 return (
72 <button
73 className={'jp-NotebookTrustedStatus'}
74 style={!trusted ? { cursor: 'pointer' } : { cursor: 'help' }}
75 onClick={() => !trusted && trust()}
76 title={
77 trusted
78 ? trans.__('JavaScript enabled for notebook display')
79 : trans.__('JavaScript disabled for notebook display')
80 }
81 >
82 {trusted ? trans.__('Trusted') : trans.__('Not Trusted')}
83 </button>
84 );
85 };
86
87 /**
88 * A namespace for TrustedComponent static methods.
89 */
90 export namespace TrustedComponent {
91 /**
92 * Create a new TrustedComponent
93 *
94 * @param notebook The notebook
95 * @param translator The translator
96 */
97 export const create = ({
98 notebook,
99 translator,
100 }: {
101 notebook: Notebook;
102 translator: ITranslator;
103 }): ReactWidget => {
104 return ReactWidget.create(
105 <TrustedButton notebook={notebook} translator={translator} />
106 );
107 };
108 }