Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Importing local notebook #20

Open
nicola opened this issue Apr 20, 2020 · 3 comments
Open

Importing local notebook #20

nicola opened this issue Apr 20, 2020 · 3 comments

Comments

@nicola
Copy link

nicola commented Apr 20, 2020

What is your strategy for importing local notebooks (I also want to keep supporting importing them from observablehq)?

@bryangingechen
Copy link
Contributor

If you put your local notebook modules in notebooks/, you could try something like this (not tested, but hopefully you see the idea)?

// copied from src/utils.js
const extractPath = path => {
  let source = path;
  let m;

  // "https://api.observablehq.com/@jashkenas/inputs.js?v=3" => strip off ".js"
  if ((m = /\.js(\?|$)/i.exec(source))) source = source.slice(0, m.index);

  // "74f872c4fde62e35" => "d/..."
  if ((m = /^[0-9a-f]{16}$/i.test(source))) source = `d/${source}`;

  // link of notebook
  if ((m = /^https:\/\/(api\.|beta\.|)observablehq\.com\//i.exec(source)))
    source = source.slice(m[0].length);
  return source;
};

// copied from src/compiler.js
const defaultResolver = async path => {
  const source = extractPath(path);
  return import(`https://api.observablehq.com/${source}.js?v=3`).then(
    m => m.default
  );
};

const resolve = async path => {
  let module;
  try {
    // look for the notebook module on observablehq.com
    return await defaultResolver(path);
  } catch (e) { // if loading fails
    // look for the notebook module in the notebooks/ directory
    const source = extractPath(path);
    return (await import(`notebooks/${source}.js`)).default;
  }
};

const compile = new Compiler(resolve);

You could also write logic in the resolve function that parses the notebook name to decide where to load a notebook module from. E.g. if your notebook has:

import {cell} from "local/notebook"

Then your resolve function is passed local/notebook and it could detect that it starts with local and act accordingly.

@nicola
Copy link
Author

nicola commented Apr 24, 2020

awesome I will try this soon! we should make this somehow a default in the library

@RandomFractals
Copy link

RandomFractals commented Oct 15, 2020

btw, I am planning to use this lib for importing local and remote ojs notebooks in this ext. for vscode I've been working on:

https://github.com/RandomFractals/js-notebook-inspector

relevant issue in my repo: RandomFractals/js-notebook-inspector#29

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants