zobweyt
zobweyt
Explore posts from servers
SSolidJS
Created by zobweyt on 10/13/2024 in #support
Using JSX in custom directives
Suppose you want to create a convenient tooltip directive that can be easily used by providing only the content of it. This works fine for simple tooltips. However, what if you want to create more complex, custom tooltips? For example, you want to wrap the element as a trigger and use it in combination with a component from libraries like https://kobalte.dev/docs/core/components/tooltip or https://corvu.dev/docs/primitives/tooltip
import { type Accessor, createEffect, createSignal } from "solid-js";
import { render } from "solid-js/web";

export default function tooltip(el: HTMLElement, title: Accessor<string>) {
createEffect(() => {
el.title = title();
});
}

declare module "solid-js" {
namespace JSX {
interface DirectiveFunctions {
tooltip: typeof tooltip;
}
}
}

function App() {
const [count, setCount] = createSignal<number>(0);

return (
<button
onClick={() => setCount((c) => c + 1)}
use:tooltip="Push to increment count"
>
{count()}
</button>
);
}

render(() => <App />, document.getElementById("app")!);
import { type Accessor, createEffect, createSignal } from "solid-js";
import { render } from "solid-js/web";

export default function tooltip(el: HTMLElement, title: Accessor<string>) {
createEffect(() => {
el.title = title();
});
}

declare module "solid-js" {
namespace JSX {
interface DirectiveFunctions {
tooltip: typeof tooltip;
}
}
}

function App() {
const [count, setCount] = createSignal<number>(0);

return (
<button
onClick={() => setCount((c) => c + 1)}
use:tooltip="Push to increment count"
>
{count()}
</button>
);
}

render(() => <App />, document.getElementById("app")!);
https://playground.solidjs.com/anonymous/eb41151c-59ca-460f-aa45-26ea80525e01 Is it possible to use JSX inside the directive to wrap the <button> with a <Tooltip> component?
7 replies
KPCKevin Powell - Community
Created by zobweyt on 10/11/2024 in #front-end
Choosing between dependencies and dev dependencies
I understand various types of dependencies when making libraries, but I still can't figure out whether it's worth dividing dependencies into different groups for applications. Let's say I use Vite, and how do I figure out where to put it? I use it for building and for running the app after it's built in production. So do I actually use it for production? Should I put such builders and runners as Vite in regular dependencies? Also, I use SASS. I know that It's needed for the building stage only. So should it be a development dependency? This leads me to another question: is building considered part of the production or development stage? Should dependencies required for the build process be placed in development dependencies or regular dependencies?
45 replies
SSolidJS
Created by zobweyt on 8/8/2024 in #support
Endless "[vite] ✨ optimized dependencies changed. reloading"
Could anyone explain why it takes an exorbitant amount of time to optimize dependencies after installing any package from npm/pnpm/yarn? This issue seems to occur randomly during development and provides a terrible developer experience (DX). Additionally, if I manually stop the dev server and try to run it again, it just says:
[get-port] Unable to find an available port (tried 3000 on host "localhost"). Using alternative port 3001.
[get-port] Unable to find an available port (tried 3000 on host "localhost"). Using alternative port 3001.
Steps to reproduce: 1. Execute pnpm create solid and pick the default options. 2. Execute pnpm dev, open the app in the browser, and then end the process. 3. Install any dependency (@solid-primitives/event-listener in this case). 4. Go to Counter.tsx and modify it to use the newly installed dependency. 5. Execute pnpm dev. 6. Go to the web browser and navigate to a page where the Counter component is not yet rendered (e.g., /about in this case). 7. Go to the /index page (the route where the Counter component should be rendered). 8. Observe the Vite optimization process, which never seems to complete in the console.
5 replies
KPCKevin Powell - Community
Created by zobweyt on 8/7/2024 in #front-end
Using CSS selectors with @media queries
Hey! I want user to select between dark, light, and system themes (and maybe even third, fourth, etc). I came up with this pen in mind: https://codepen.io/zobweyt/pen/BagdyGq But it's not working as expected. I want to turn on dark styles when any of the following conditions satisfy: - There's [data-theme="dark"] on an element - There's [data-theme="system"] on an element with @media (prefers-color-scheme: dark) I can't find a solution to make it without copy-pasting and mixins from SCSS or PostCSS, etc Is it even possible?
7 replies
SSolidJS
Created by zobweyt on 7/26/2024 in #support
Context with children(() => props.children) helper triggers an error
Hey! I've been trying to create a Stepper component in which I'd have StepperContext with its API. however, somehow I need to control the displayed children, I found the children helper but it doesn't work with context https://playground.solidjs.com/anonymous/92dca985-17bc-4cbb-b2d8-d4b95fb33a33 am I missing something?
140 replies
SSolidJS
Created by zobweyt on 7/14/2024 in #support
Redirecting on protected routes
Hey! Is there any recommended way to do route protecting on the server with SSR? For example, I need to redirect users from protected routes to the previous URL, if exists on router. Here's my current implementation:
type Session = { token: string | undefined };

const OPTIONS: SessionConfig = {
password: process.env.SESSION_SECRET,
};

export const getSession = async () => {
return await useSession<Session>(OPTIONS);
};

export const redirectUnauthenticated = cache(async (url: string) => {
"use server";
const session = await getSession();
if (session.data.token === undefined) {
throw redirect(url);
}
return {};
}, "redirectUnauthenticated");

export const createRedirectUnauthenticated = (url: string = "/login") => {
createAsync(() => redirectUnauthenticated(url));
};

export default function Page() {
createRedirectUnauthenticated("/login?redirect=/profile");

return ...
}
type Session = { token: string | undefined };

const OPTIONS: SessionConfig = {
password: process.env.SESSION_SECRET,
};

export const getSession = async () => {
return await useSession<Session>(OPTIONS);
};

export const redirectUnauthenticated = cache(async (url: string) => {
"use server";
const session = await getSession();
if (session.data.token === undefined) {
throw redirect(url);
}
return {};
}, "redirectUnauthenticated");

export const createRedirectUnauthenticated = (url: string = "/login") => {
createAsync(() => redirectUnauthenticated(url));
};

export default function Page() {
createRedirectUnauthenticated("/login?redirect=/profile");

return ...
}
However, this implementation is not the best because it shows the Page to an unauthorized user for a few milliseconds before redirecting. In addition, if using the snippet below for the Page route, it won't show the Page to user for a few milliseconds before redirecting, but it can run the preload at any state of my app, which will break all redirects and always redirect to /login?redirect=/profile instead of the ?redirect parameter:
export const route = {
preload: () => createRedirectUnauthenticated("/login?redirect=/profile"),
} satisfies RouteDefinition;
export const route = {
preload: () => createRedirectUnauthenticated("/login?redirect=/profile"),
} satisfies RouteDefinition;
Before, I tried using useNavigate, but the code needs to be run on the client in this case. However, I need to perform this check on the server first. Also, as I mentioned before, I want always to redirect the unauthorized user to the previous URL. I tried doing it with event?.router?.previousUrl from getRequestEvent() in redirectUnauthenticated function, but it's always returns undefied. How can I solve this issue correctly?
24 replies
CC#
Created by zobweyt on 4/12/2024 in #help
Attributes confusion
hey! I'm having trouble choosing an approach when using attributes. I'm building a wrapper around System.Threading.RateLimiting. I have an attribute RateLimitAttribute which is responsible for the basic logic and creation of PartitionedRateLimiter. here’s the problem: I want to be able to create custom ignore policies (to have no limit in custom conditions) and pass them directly to the RateLimitAttribute, but I don’t know how to do this correctly and what approach to choose. initially I wanted to make a base class RateLimitPolicyAttribute for all policies and later use it like this:
[RateLimit]
[IgnoreOwner, IgnoreAdmins, IgnorePremiumUsers]
public static void Foo() => throw NotImplementedException();
[RateLimit]
[IgnoreOwner, IgnoreAdmins, IgnorePremiumUsers]
public static void Foo() => throw NotImplementedException();
but the policies here can exist without the main RateLimitAttribute also, I thought about passing the policies directly to the main attribute, but this approach is not possible because the values in attribute parameters must be constant, so I can't just pass a list of policies. additionally, it'll be a very long line in length if I have many policies how can I implement this most conveniently?
21 replies
CC#
Created by zobweyt on 1/25/2024 in #help
Implementing rate limiting for discord bot interactions with absolute expiration of items
I’m trying to create a simple and customizable RateLimitAttribute for interactions in Discord.Net using their preconditions. I'm too confused about all the possibilities. So, how would you implement this? What decisions would you make and what data structures would you use? Expected usage
[RateLimit(max: 2, period: TimeSpan.FromMinutes(1), ignore: Ignore.Owner | Ignore.DMs)]
[SlashCommand("ping", "Pings the bot.")]
public async Task PingAsync() => await RespondAsync("Pong!");
[RateLimit(max: 2, period: TimeSpan.FromMinutes(1), ignore: Ignore.Owner | Ignore.DMs)]
[SlashCommand("ping", "Pings the bot.")]
public async Task PingAsync() => await RespondAsync("Pong!");
Expected behavior /ping — Pong! (count is now 1) /ping — Pong! (count is now 2) /ping — Wait 60 seconds for limit to expire! /ping (30 seconds later) — Wait 30 seconds for limit to expire! … (30 seconds later)Remove rate limit from store in background. /ping (any time later) — Pong! (count is now 1) Wanted features: - Users can define custom ignore policies: for instance, if you have a database with different roles like admins and regular users, you might want to apply rate limiting to all users but exclude admins. - Users can access the store of rate limits: for example, EPIC RPG’s /cd command shows the cooldowns for each command per user. Problems I’ve met - Attributes require constant values: TimeSpan cannot be used directly. Instead, people use parameters specifying periods in seconds. Alternatively, a converter could be used with double period and enum TimeMeasure. - Caching with absolute expiration: IMemoryCache's AbsoluteExpiration simplifies caching implementation because it removes the rate limits right when they expire, but the keys there are strings and not generic types. Using System.Threading.RateLimiting, it’s hard to display the exact remaining time until the limit expires.
5 replies
CC#
Created by zobweyt on 7/16/2023 in #help
✅ What is the best way to setup app configuration using IHostBuilder?
I want to make a good building of my host configuration and make it convenient to use. My goal is to get the as much as possible: - Convenience; - Strongly typing; - Won't compile against typos in keys; I've already tried those ways to setup configuration and found them inconvenient: 1. HostBuilderContext.Configuration["Key"] · hardcoding keys; 2. context.Configuration.Get<Configuration>() · calling the same method everywhere; 3. context.Configuration.Bind(configuration) · confusing where to bind it at the first time; Personally I'm using the third way, because it saves me from code duplication and hardcoding keys, but also brings a new problem — confusing where to bind the configuration. Currently, I'm binding it in the IHostBuilder.ConfigureAppConfiguration:
internal class Program
{
private static readonly Configuration _configuration = new();

private static async Task Main(string[] args)
{
var host = Host.CreateDefaultBuilder(args)
.ConfigureAppConfiguration(b => b.Build().Bind(_configuration))
.ConfigureServices((context, services) =>
{
services.AddSingleton(_configuration);
})
.Build();

await host.RunAsync();
}
}
internal class Program
{
private static readonly Configuration _configuration = new();

private static async Task Main(string[] args)
{
var host = Host.CreateDefaultBuilder(args)
.ConfigureAppConfiguration(b => b.Build().Bind(_configuration))
.ConfigureServices((context, services) =>
{
services.AddSingleton(_configuration);
})
.Build();

await host.RunAsync();
}
}
Ideally, I would like to redefine content.Configuration so that its type matches Configuration (my custom class), in order to directly get values without hardcoding, for example: context.Configuration.Token. But I understand that this may not be possible.
6 replies
CC#
Created by zobweyt on 12/23/2022 in #help
❔ Naming fields meaning numbers
6 replies