spencermountain / spacetime

A lightweight javascript timezone library
http://spacetime.how/
Other
3.98k stars 184 forks source link

Question about making plugins #392

Closed Mitsunee closed 1 year ago

Mitsunee commented 1 year ago

Hello, I just made spacetime-to-discord on a whim.

Is there any documentation on how I could turn this into a spacetime plugin? I had a peek at some of the existing plugins and couldn't figure out how they are handled in TypeScript types, which I'd need to work for my projects.

spencermountain commented 1 year ago

hey cool! yeah, from what I can tell, discord timestamps just take an epoch? I mean, you could use Date.now() / 1000 for that - a spacetime plugin may be overkill. Let me know if I'm missing something - i'm no good at typescript, either cheers

Mitsunee commented 1 year ago

Hello, just wanted to update you on something I stumbled upon that ended up helping me with this issue:

declare module "spacetime" {
  interface Spacetime {
    toDiscord: (style?: Style) => string;
  }
}

using declare module "spacetime" like this allows my code (that also registers the plugin with spacetime.extend) to modify the Spacetime interface to add the type of my plugin. Now there's a sideeffect import to register my plugin + its type:

import "spacetime-to-discord/plugin";

const s = spacetime.now();
const str = s.toDiscord("nice"); // "<t:1690139640:f>"

Closing the issue since I solved what I intended to ask about here :)

spencermountain commented 1 year ago

oh yeah - this is a head-scratcher for me too. I've never been sure the proper way to do this. Honestly, I may be the worst person to ask - typescript confounds me constantly.

Being able to modify stuff is what makes javascript cool - please let me know if you find a good solution, or if we can export something to help this pattern.

You can see the current plugins aren't typed because I haven't figured out how. cheers

Mitsunee commented 1 year ago

I think my solution should be sufficient. There isn't really a way to make calling a function change an interface, so using declare like this seems to be the only way. Might feel a bit redundant, but I'm happy with the solution :)