Code for the obsidian spreadsheets added

This commit is contained in:
Divam Gupta 2023-08-07 20:36:22 -04:00
parent 7112f01bc6
commit 1eda02ab94
14 changed files with 6705 additions and 161 deletions

21
LICENSE Normal file
View file

@ -0,0 +1,21 @@
MIT License
Copyright (c) 2022 Suzhou Ruilisi Technology Co., Ltd
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View file

@ -1,96 +1,34 @@
# Obsidian Sample Plugin # Obsidian Spreadsheets Plugin
This is a sample plugin for Obsidian (https://obsidian.md). This plugin gives you all the features of a standard spreadsheets tool in obsidian. You can build powerful spreadsheets within obsidian.
This project uses Typescript to provide type checking and documentation. This plugin is based on FortuneSheet, which is based on Luckysheet.
The repo depends on the latest plugin API (obsidian.d.ts) in Typescript Definition format, which contains TSDoc comments describing what it does.
**Note:** The Obsidian API is still in early alpha and is subject to change at any time! ### Features:
This sample plugin demonstrates some of the basic functionality the plugin API can do. - Rich text formatting - change fonts, size, colors, borders, cell color, line-wrapping, etc
- Adds a ribbon icon, which shows a Notice when clicked.
- Adds a command "Open Sample Modal" which opens a Modal.
- Adds a plugin setting tab to the settings page.
- Registers a global click event and output 'click' to the console.
- Registers a global interval which logs 'setInterval' to the console.
## First time developing plugins? - Formulas - several build in formulas
Quick starting guide for new plugin devs: - Filter and sort
- Check if [someone already developed a plugin for what you want](https://obsidian.md/plugins)! There might be an existing plugin similar enough that you can partner up with. - Cells - merge cells, resize cells, drag cells
- Make a copy of this repo as a template with the "Use this template" button (login to GitHub if you don't see it).
- Clone your repo to a local development folder. For convenience, you can place this folder in your `.obsidian/plugins/your-plugin-name` folder.
- Install NodeJS, then run `npm i` in the command line under your repo folder.
- Run `npm run dev` to compile your plugin from `main.ts` to `main.js`.
- Make changes to `main.ts` (or create new `.ts` files). Those changes should be automatically compiled into `main.js`.
- Reload Obsidian to load the new version of your plugin.
- Enable plugin in settings window.
- For updates to the Obsidian API run `npm update` in the command line under your repo folder.
## Releasing new releases
- Update your `manifest.json` with your new version number, such as `1.0.1`, and the minimum Obsidian version required for your latest release.
- Update your `versions.json` file with `"new-plugin-version": "minimum-obsidian-version"` so older versions of Obsidian can download an older version of your plugin that's compatible.
- Create new GitHub release using your new version number as the "Tag version". Use the exact version number, don't include a prefix `v`. See here for an example: https://github.com/obsidianmd/obsidian-sample-plugin/releases
- Upload the files `manifest.json`, `main.js`, `styles.css` as binary attachments. Note: The manifest.json file must be in two places, first the root path of your repository and also in the release.
- Publish the release.
> You can simplify the version bump process by running `npm version patch`, `npm version minor` or `npm version major` after updating `minAppVersion` manually in `manifest.json`. ### Screenshots:
> The command will bump version in `manifest.json` and `package.json`, and add the entry for the new version to `versions.json`
## Adding your plugin to the community plugin list ### ![screen1](assets/screen1.png)
- Check https://github.com/obsidianmd/obsidian-releases/blob/master/plugin-review.md ![screen2](assets/screen2.png)
- Publish an initial version.
- Make sure you have a `README.md` file in the root of your repo.
- Make a pull request at https://github.com/obsidianmd/obsidian-releases to add your plugin.
## How to use
- Clone this repo.
- Make sure your NodeJS is at least v16 (`node --version`).
- `npm i` or `yarn` to install dependencies.
- `npm run dev` to start compilation in watch mode.
## Manually installing the plugin ![screen3](assets/screen3.png)
- Copy over `main.js`, `styles.css`, `manifest.json` to your vault `VaultFolder/.obsidian/plugins/your-plugin-id/`. ![screen3](assets/screen4.png)
## Improve code quality with eslint (optional)
- [ESLint](https://eslint.org/) is a tool that analyzes your code to quickly find problems. You can run ESLint against your plugin to find common bugs and ways to improve your code.
- To use eslint with this project, make sure to install eslint from terminal:
- `npm install -g eslint`
- To use eslint to analyze this project use this command:
- `eslint main.ts`
- eslint will then create a report with suggestions for code improvement by file and line number.
- If your source code is in a folder, such as `src`, you can use eslint with this command to analyze all files in that folder:
- `eslint .\src\`
## Funding URL
You can include funding URLs where people who use your plugin can financially support it. ![screen5](assets/screen5.png)
The simple way is to set the `fundingUrl` field to your link in your `manifest.json` file:
```json
{
"fundingUrl": "https://buymeacoffee.com"
}
```
If you have multiple URLs, you can also do:
```json
{
"fundingUrl": {
"Buy Me a Coffee": "https://buymeacoffee.com",
"GitHub Sponsor": "https://github.com/sponsors",
"Patreon": "https://www.patreon.com/"
}
}
```
## API Documentation
See https://github.com/obsidianmd/obsidian-api

BIN
assets/screen1.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 806 KiB

BIN
assets/screen2.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 MiB

BIN
assets/screen3.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 860 KiB

BIN
assets/screen4.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 980 KiB

BIN
assets/screen5.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 791 KiB

2963
main.css Normal file

File diff suppressed because one or more lines are too long

155
main.ts
View file

@ -1,81 +1,111 @@
import { App, Editor, MarkdownView, Modal, Notice, Plugin, PluginSettingTab, Setting } from 'obsidian'; import { App, Editor, MarkdownView, Notice, Plugin, PluginSettingTab, Setting, WorkspaceLeaf } from 'obsidian';
import { SpreadsheetView, VIEW_TYPE_SPREADSHEET } from "./view"
// Remember to rename these classes and interfaces! // Remember to rename these classes and interfaces!
interface MyPluginSettings { interface SpreadsheetPluginSettings {
mySetting: string; mySetting: string;
} }
const DEFAULT_SETTINGS: MyPluginSettings = { const DEFAULT_SETTINGS: SpreadsheetPluginSettings = {
mySetting: 'default' mySetting: 'default'
} }
export default class MyPlugin extends Plugin {
settings: MyPluginSettings;
async function create_new_file(app, folder_path, file_no){
if(folder_path){
try {
await app.vault.createFolder(folder_path);
} catch (err) {
console.log("issue in making folder");
console.log(err);
}
}
let file_name = "Untitled.sheet"
if(file_no){
file_name = "Untitled"+ file_no +".sheet"
}
let file_path = file_name;
if(folder_path){
file_path = folder_path + "/" + file_name;
}
try {
await app.vault.create(file_path, "");
await app.workspace.getLeaf(true).setViewState({
type: VIEW_TYPE_SPREADSHEET,
active: true,
state: { file: file_path }
});
new Notice('Create spreadsheet at : ' + file_path);
} catch (err) {
const error = err;
if (error.message.includes("File already exists")) {
return await create_new_file(app , folder_path , (file_no||0)+1 )
}
}
}
export default class SpreadsheetPlugin extends Plugin {
settings: SpreadsheetPluginSettings;
async onload() { async onload() {
await this.loadSettings(); await this.loadSettings();
// This creates an icon in the left ribbon. // This creates an icon in the left ribbon.
const ribbonIconEl = this.addRibbonIcon('dice', 'Sample Plugin', (evt: MouseEvent) => { const ribbonIconEl = this.addRibbonIcon('table', 'New Spreadsheet', (evt: MouseEvent) => {
// Called when the user clicks the icon. // Called when the user clicks the icon.
new Notice('This is a notice!'); create_new_file(this.app);
}); });
// Perform additional things with the ribbon // Perform additional things with the ribbon
ribbonIconEl.addClass('my-plugin-ribbon-class'); ribbonIconEl.addClass('my-plugin-ribbon-class');
// This adds a status bar item to the bottom of the app. Does not work on mobile apps.
const statusBarItemEl = this.addStatusBarItem();
statusBarItemEl.setText('Status Bar Text');
// This adds a simple command that can be triggered anywhere let that = this;
this.addCommand({
id: 'open-sample-modal-simple', this.registerEvent(
name: 'Open sample modal (simple)', this.app.workspace.on("file-menu", (menu, file) => {
callback: () => { menu.addItem((item) => {
new SampleModal(this.app).open(); item.setTitle("New spreadsheet").setIcon("document").onClick(function(){
} create_new_file(that.app, file.path, 0 )
}); });
// This adds an editor command that can perform some operation on the current editor instance });
this.addCommand({ })
id: 'sample-editor-command', );
name: 'Sample editor command',
editorCallback: (editor: Editor, view: MarkdownView) => {
console.log(editor.getSelection());
editor.replaceSelection('Sample Editor Command');
}
});
// This adds a complex command that can check whether the current state of the app allows execution of the command
this.addCommand({
id: 'open-sample-modal-complex',
name: 'Open sample modal (complex)',
checkCallback: (checking: boolean) => {
// Conditions to check
const markdownView = this.app.workspace.getActiveViewOfType(MarkdownView);
if (markdownView) {
// If checking is true, we're simply "checking" if the command can be run.
// If checking is false, then we want to actually perform the operation.
if (!checking) {
new SampleModal(this.app).open();
}
// This command will only show up in Command Palette when the check function returns true
return true;
}
}
});
// This adds a settings tab so the user can configure various aspects of the plugin // This adds a settings tab so the user can configure various aspects of the plugin
this.addSettingTab(new SampleSettingTab(this.app, this)); this.addSettingTab(new SampleSettingTab(this.app, this));
// If the plugin hooks up any global DOM events (on parts of the app that doesn't belong to this plugin)
// Using this function will automatically remove the event listener when this plugin is disabled.
this.registerDomEvent(document, 'click', (evt: MouseEvent) => {
console.log('click', evt);
});
// When registering intervals, this function will automatically clear the interval when the plugin is disabled. // When registering intervals, this function will automatically clear the interval when the plugin is disabled.
this.registerInterval(window.setInterval(() => console.log('setInterval'), 5 * 60 * 1000)); this.registerInterval(window.setInterval(() => console.log('setInterval'), 5 * 60 * 1000));
this.registerView(
VIEW_TYPE_SPREADSHEET,
(leaf: WorkspaceLeaf) => new SpreadsheetView(leaf)
);
this.registerExtensions(["sheet"], VIEW_TYPE_SPREADSHEET);
} }
onunload() { onunload() {
@ -91,26 +121,11 @@ export default class MyPlugin extends Plugin {
} }
} }
class SampleModal extends Modal {
constructor(app: App) {
super(app);
}
onOpen() {
const {contentEl} = this;
contentEl.setText('Woah!');
}
onClose() {
const {contentEl} = this;
contentEl.empty();
}
}
class SampleSettingTab extends PluginSettingTab { class SampleSettingTab extends PluginSettingTab {
plugin: MyPlugin; plugin: SpreadsheetPlugin;
constructor(app: App, plugin: MyPlugin) { constructor(app: App, plugin: SpreadsheetPlugin) {
super(app, plugin); super(app, plugin);
this.plugin = plugin; this.plugin = plugin;
} }
@ -121,10 +136,10 @@ class SampleSettingTab extends PluginSettingTab {
containerEl.empty(); containerEl.empty();
new Setting(containerEl) new Setting(containerEl)
.setName('Setting #1') .setName('Setting')
.setDesc('It\'s a secret') .setDesc('settings')
.addText(text => text .addText(text => text
.setPlaceholder('Enter your secret') .setPlaceholder('...')
.setValue(this.plugin.settings.mySetting) .setValue(this.plugin.settings.mySetting)
.onChange(async (value) => { .onChange(async (value) => {
this.plugin.settings.mySetting = value; this.plugin.settings.mySetting = value;

View file

@ -1,11 +1,10 @@
{ {
"id": "sample-plugin", "id": "spreadsheets-plugin",
"name": "Sample Plugin", "name": "Spreadsheets",
"version": "1.0.0", "version": "1.0.0",
"minAppVersion": "0.15.0", "minAppVersion": "0.15.0",
"description": "This is a sample plugin for Obsidian. This plugin demonstrates some of the capabilities of the Obsidian API.", "description": "Plugin to create spreadsheets in obsidian.",
"author": "Obsidian", "author": "Divam Gupta",
"authorUrl": "https://obsidian.md", "authorUrl": "https://divam.io",
"fundingUrl": "https://obsidian.md/pricing", "isDesktopOnly": true
"isDesktopOnly": false
} }

View file

@ -1,7 +1,7 @@
{ {
"name": "obsidian-sample-plugin", "name": "spreadsheets-plugin",
"version": "1.0.0", "version": "1.0.0",
"description": "This is a sample plugin for Obsidian (https://obsidian.md)", "description": "Plugin to create spreadsheets in obsidian",
"main": "main.js", "main": "main.js",
"scripts": { "scripts": {
"dev": "node esbuild.config.mjs", "dev": "node esbuild.config.mjs",
@ -13,6 +13,8 @@
"license": "MIT", "license": "MIT",
"devDependencies": { "devDependencies": {
"@types/node": "^16.11.6", "@types/node": "^16.11.6",
"@types/react": "^18.2.18",
"@types/react-dom": "^18.2.7",
"@typescript-eslint/eslint-plugin": "5.29.0", "@typescript-eslint/eslint-plugin": "5.29.0",
"@typescript-eslint/parser": "5.29.0", "@typescript-eslint/parser": "5.29.0",
"builtin-modules": "3.3.0", "builtin-modules": "3.3.0",
@ -20,5 +22,10 @@
"obsidian": "latest", "obsidian": "latest",
"tslib": "2.4.0", "tslib": "2.4.0",
"typescript": "4.7.4" "typescript": "4.7.4"
},
"dependencies": {
"@fortune-sheet/react": "^0.19.0",
"react": "^18.2.0",
"react-dom": "^18.2.0"
} }
} }

3434
styles.css

File diff suppressed because it is too large Load diff

View file

@ -1,5 +1,6 @@
{ {
"compilerOptions": { "compilerOptions": {
"jsx": "react",
"baseUrl": ".", "baseUrl": ".",
"inlineSourceMap": true, "inlineSourceMap": true,
"inlineSources": true, "inlineSources": true,

176
view.tsx Normal file
View file

@ -0,0 +1,176 @@
import { TextFileView } from "obsidian";
export const VIEW_TYPE_SPREADSHEET = "spreadsheet-view";
import { ItemView, WorkspaceLeaf } from "obsidian";
import * as React from "react";
import * as ReactDOM from "react-dom";
import { createRoot } from "react-dom/client";
import { Workbook } from "@fortune-sheet/react";
import "@fortune-sheet/react/dist/index.css"
function set_ctx_pos(el) {
let rect=el.getBoundingClientRect();
let p = {x:rect.left,y:rect.top};
let r = document.querySelector(':root');
if(p.x){
r.style.setProperty('--ctx_menu_x', -1*p.x + "px" );
r.style.setProperty('--ctx_menu_y', (-1*p.y + 50 )+ "px" );
}
// console.log("pos is set to ")
// console.log( -1*p.x + "px")
// console.log( (-1*p.y + 50 )+ "px" )
}
function transformData(responseData) {
return responseData.map((sheet) => ({
id: sheet.id,
name: sheet.name,
plugin: "divams_spreadsheets_for_obsidian",
config: sheet.config,
celldata: (sheet.data || []).flatMap((row, rIndex) =>
row
.map((cell, cIndex) => {
if (cell !== null) {
return {
r: rIndex,
c: cIndex,
v: cell,
};
}
return undefined;
})
.filter((cell) => cell !== undefined),
),
calcChain: (sheet.calcChain || []).map((item) => {
const relatedCell = sheet.data[item.r][item.c];
return {
r: item.r,
c: item.c,
id: item.id,
v: relatedCell !== null ? relatedCell : null,
};
}),
}));
}
function handleData(receivedData) {
const newData = transformData(receivedData);
if (receivedData.length > 0 && receivedData[0].calcChain) {
newData[0].calcChain = receivedData[0].calcChain;
}
return newData;
}
export class SpreadsheetView extends TextFileView {
table_element: HTMLElement;
spreadsheet_container : HTMLElement;
sheet_data_in : any;
sheet_data_out : any;
root : any;
is_save_timer_wait : any;
resize_observer : any;
getViewData() {
if(this.sheet_data_out){
let r = JSON.stringify( handleData(this.sheet_data_out) , null, 4 ) ;
console.log("saved!!")
return r;
} else {
return ""
}
}
// If clear is set, then it means we're opening a completely different file.
setViewData(data: string, clear: boolean) {
if(data.trim()){
this.sheet_data_in = JSON.parse(data)
} else {
this.sheet_data_in = [{ name: "Sheet1" }];
}
this.refresh();
}
refresh() {
this.table_element.empty();
let spreadsheet_container = this.table_element.createEl("div");
spreadsheet_container.setAttribute("style","background-color:black; width:calc(100% - 15px) ; height: calc( 100vh - 130px); color:black ; ")
// add filter: invert(1); for dark mode #TODO: make a button in settings page
this.resize_observer = new ResizeObserver(function(){
window.dispatchEvent(new Event('resize'));
set_ctx_pos(spreadsheet_container)
}).observe(spreadsheet_container)
//
this.spreadsheet_container = spreadsheet_container;
let that = this;
const settings = {
data: this.sheet_data_in, // sheet data
onChange: (data:any) => { that.sheet_data_out = data; that.maybe_save_data()}, // onChange event
}
this.root = createRoot(spreadsheet_container);
this.root.render(
<Workbook {...settings} />
);
}
maybe_save_data(){
let that = this;
if(that.is_save_timer_wait)
return;
that.is_save_timer_wait = true;
setTimeout(function(){
that.requestSave();
that.is_save_timer_wait = false;
} , 4000 )
}
clear() {
}
getViewType() {
return VIEW_TYPE_SPREADSHEET;
}
async onOpen() {
this.table_element = this.contentEl.createEl("div");
}
async onClose() {
if(this.resize_observer){
this.resize_observer.disconnect()
}
this.requestSave();
if(this.root)
this.root.unmount()
this.contentEl.empty();
}
}