Skip to content

Commit

Permalink
Show a picture in the panel
Browse files Browse the repository at this point in the history
  • Loading branch information
Zhiming Zhang committed Nov 9, 2023
1 parent 7fc9c7a commit 7385067
Showing 1 changed file with 39 additions and 5 deletions.
44 changes: 39 additions & 5 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,16 @@ import {

import { ICommandPalette, MainAreaWidget } from '@jupyterlab/apputils';
import { Widget } from '@lumino/widgets';

interface APODResponse {
copyright: string;
date: string;
explanation: string;
media_type: 'video' | 'image';
title: string;
url: string;
};

/**
* Initialization data for the jupyterlab_apod extension.
*/
Expand All @@ -13,30 +23,54 @@ const plugin: JupyterFrontEndPlugin<void> = {
description: 'A JupyterLab extension.',
autoStart: true,
requires: [ICommandPalette],
activate: (app: JupyterFrontEnd, palette: ICommandPalette) => {
activate: async (app: JupyterFrontEnd, palette: ICommandPalette) => {
console.log('JupyterLab extension jupyterlab_apod is activated!');

// Define a widget creator function,
// then call it to make a new widget
const newWidget = () => {
const newWidget = async () => {
// Create a blank content widget inside of a MainAreaWidget
const content = new Widget();
const widget = new MainAreaWidget({ content });
widget.id = 'apod-jupyterlab';
widget.title.label = 'Astronomy Picture';
widget.title.closable = true;

// Add an image element to the content
let img = document.createElement('img');
content.node.appendChild(img);

// Get a random date string in YYYY-MM-DD format
function randomDate() {
const start = new Date(2010, 1, 1);
const end = new Date();
const randomDate = new Date(start.getTime() + Math.random()*(end.getTime() - start.getTime()));
return randomDate.toISOString().slice(0, 10);
}

// Fetch info about a random picture
const response = await fetch(`https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY&date=${randomDate()}`);
const data = await response.json() as APODResponse;

if (data.media_type === 'image') {
// Populate the image
img.src = data.url;
img.title = data.title;
} else {
console.log('Random APOD was not a picture.');
}
return widget;
}
let widget = newWidget();
let widget = await newWidget();

// Add an application command
const command: string = 'apod:open';
app.commands.addCommand(command, {
label: 'Random Astronomy Picture',
execute: () => {
execute: async () => {
// Regenerate the widget if disposed
if (widget.isDisposed) {
widget = newWidget();
widget = await newWidget();
}
if (!widget.isAttached) {
// Attach the widget to the main work area if it's not there
Expand Down

0 comments on commit 7385067

Please sign in to comment.