@@ -0,0 +1,59 @@
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import { Spinner } from "@cohaise/ui";
|
||||
import { ApiError, api, type User } from "./lib/api.js";
|
||||
import { Login } from "./pages/Login.js";
|
||||
import { ChangePassword } from "./pages/ChangePassword.js";
|
||||
import { Crm } from "./pages/Crm.js";
|
||||
|
||||
type Session =
|
||||
| { state: "loading" }
|
||||
| { state: "guest" }
|
||||
| { state: "ready"; user: User };
|
||||
|
||||
export const App = () => {
|
||||
const [session, setSession] = useState<Session>({ state: "loading" });
|
||||
|
||||
const refresh = useCallback(async () => {
|
||||
try {
|
||||
const { user } = await api.me();
|
||||
setSession({ state: "ready", user });
|
||||
} catch (error) {
|
||||
// 401 = simplement deconnecte, ce n'est pas une panne.
|
||||
if (error instanceof ApiError && error.status === 401) setSession({ state: "guest" });
|
||||
else setSession({ state: "guest" });
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
void refresh();
|
||||
}, [refresh]);
|
||||
|
||||
const logout = useCallback(async () => {
|
||||
await api.logout().catch(() => undefined);
|
||||
setSession({ state: "guest" });
|
||||
}, []);
|
||||
|
||||
if (session.state === "loading") {
|
||||
return (
|
||||
<div className="flex min-h-dvh items-center justify-center bg-background">
|
||||
<Spinner size="md" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (session.state === "guest") {
|
||||
return <Login onAuthenticated={(user) => setSession({ state: "ready", user })} />;
|
||||
}
|
||||
|
||||
if (session.user.must_change_password) {
|
||||
return (
|
||||
<ChangePassword
|
||||
user={session.user}
|
||||
onCompleted={refresh}
|
||||
onLogout={() => void logout()}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
return <Crm user={session.user} onLogout={() => void logout()} />;
|
||||
};
|
||||
@@ -0,0 +1,870 @@
|
||||
// @ts-nocheck
|
||||
// Rendu WebGL2 « terminal » (grille de glyphes, scanlines, glitch). Porté tel
|
||||
// quel, volontairement non typé (code shader dense).
|
||||
import { useEffect, useRef } from 'react';
|
||||
|
||||
const INTRO_SECONDS = 2;
|
||||
const MAX_CLICKS = 4;
|
||||
const CLICK_SECONDS = { glitch: 0.7, degauss: 1.6 };
|
||||
const GLYPHS = { blocks: 0, dots: 1, characters: 2 };
|
||||
const CLICKS = { none: 0, glitch: 1, degauss: 2 };
|
||||
|
||||
const FONT = [
|
||||
['.###.', '#..##', '#.#.#', '##..#', '.###.'],
|
||||
['..#..', '.##..', '..#..', '..#..', '.###.'],
|
||||
['####.', '....#', '.###.', '#....', '#####'],
|
||||
['####.', '....#', '.###.', '....#', '####.'],
|
||||
['#..#.', '#..#.', '#####', '...#.', '...#.'],
|
||||
['#####', '#....', '####.', '....#', '####.'],
|
||||
['.###.', '#....', '####.', '#...#', '.###.'],
|
||||
['#####', '....#', '...#.', '..#..', '..#..'],
|
||||
['.###.', '#...#', '.###.', '#...#', '.###.'],
|
||||
['.###.', '#...#', '.####', '....#', '.###.'],
|
||||
['.###.', '#...#', '#####', '#...#', '#...#'],
|
||||
['####.', '#...#', '####.', '#...#', '####.'],
|
||||
['.####', '#....', '#....', '#....', '.####'],
|
||||
['####.', '#...#', '#...#', '#...#', '####.'],
|
||||
['#####', '#....', '####.', '#....', '#####'],
|
||||
['#####', '#....', '####.', '#....', '#....'],
|
||||
['.....', '..#..', '.###.', '..#..', '.....'],
|
||||
['.....', '.....', '.###.', '.....', '.....'],
|
||||
['.#...', '..#..', '...#.', '..#..', '.#...'],
|
||||
['....#', '...#.', '..#..', '.#...', '#....'],
|
||||
['.....', '#.#.#', '.###.', '#.#.#', '.....'],
|
||||
['.....', '#####', '.....', '#####', '.....'],
|
||||
['.....', '.....', '.....', '.....', '#####']
|
||||
];
|
||||
|
||||
const FONT_BITS = FONT.map(rows =>
|
||||
rows.reduce((bits, row, r) => {
|
||||
let value = bits;
|
||||
for (let c = 0; c < 5; c++) if (row[c] === '#') value += 2 ** (r * 5 + c);
|
||||
return value;
|
||||
}, 0)
|
||||
);
|
||||
|
||||
const VERTEX = `#version 300 es
|
||||
void main() {
|
||||
vec2 p = vec2(float((gl_VertexID << 1) & 2), float(gl_VertexID & 2));
|
||||
gl_Position = vec4(p * 2.0 - 1.0, 0.0, 1.0);
|
||||
}`;
|
||||
|
||||
const PATTERN = `
|
||||
float time;
|
||||
|
||||
float noise(vec2 p) {
|
||||
return sin(p.x * 10.0) * sin(p.y * (3.0 + sin(time * 0.090909))) + 0.2;
|
||||
}
|
||||
|
||||
mat2 rotate(float angle) {
|
||||
float c = cos(angle);
|
||||
float s = sin(angle);
|
||||
return mat2(c, -s, s, c);
|
||||
}
|
||||
|
||||
float fbm(vec2 p) {
|
||||
p *= 1.1;
|
||||
float f = 0.0;
|
||||
float amp = 0.5 * uNoiseAmp;
|
||||
mat2 modify0 = rotate(time * 0.02);
|
||||
f += amp * noise(p);
|
||||
p = modify0 * p * 2.0;
|
||||
amp *= 0.454545;
|
||||
mat2 modify1 = rotate(time * 0.02);
|
||||
f += amp * noise(p);
|
||||
p = modify1 * p * 2.0;
|
||||
amp *= 0.454545;
|
||||
f += amp * noise(p);
|
||||
return f;
|
||||
}
|
||||
|
||||
float pattern(vec2 p) {
|
||||
vec2 offset1 = vec2(1.0);
|
||||
vec2 offset0 = vec2(0.0);
|
||||
mat2 rot01 = rotate(0.1 * time);
|
||||
mat2 rot1 = rotate(0.1);
|
||||
vec2 q = vec2(fbm(p + offset1), fbm(rot01 * p + offset1));
|
||||
vec2 r = vec2(fbm(rot1 * q + offset0), fbm(q + offset0));
|
||||
return fbm(p + r);
|
||||
}
|
||||
`;
|
||||
|
||||
const CELL_FRAGMENT = `#version 300 es
|
||||
precision highp float;
|
||||
precision highp int;
|
||||
|
||||
uniform float iTime;
|
||||
uniform vec2 uGridMul;
|
||||
uniform float uNoiseAmp;
|
||||
uniform float uScale;
|
||||
uniform vec2 uMouse;
|
||||
uniform float uMouseStrength;
|
||||
uniform float uUseMouse;
|
||||
uniform float uPageLoadProgress;
|
||||
uniform float uUsePageLoadAnimation;
|
||||
uniform ivec2 uOrigin;
|
||||
uniform sampler2D uPrev0;
|
||||
uniform sampler2D uPrev1;
|
||||
uniform float uDecay;
|
||||
uniform float uFresh;
|
||||
uniform float uHover;
|
||||
|
||||
layout(location = 0) out vec4 outRings;
|
||||
layout(location = 1) out vec4 outExtra;
|
||||
${PATTERN}
|
||||
void main() {
|
||||
time = iTime * 0.333333;
|
||||
ivec2 texel = ivec2(gl_FragCoord.xy);
|
||||
vec2 grid = uGridMul * 15.0;
|
||||
vec2 s = vec2(texel + uOrigin) / grid;
|
||||
float intensity = pattern(s * 0.1) * 1.3 - 0.03;
|
||||
float lift = 0.0;
|
||||
float strike = 0.0;
|
||||
|
||||
if (uUseMouse > 0.5) {
|
||||
vec2 mouseWorld = uMouse * uScale;
|
||||
float distToMouse = distance(s, mouseWorld);
|
||||
float mouseInfluence = exp(-distToMouse * 8.0) * uMouseStrength * 10.0;
|
||||
intensity += mouseInfluence;
|
||||
float ripple = sin(distToMouse * 20.0 - iTime * 5.0) * 0.1 * mouseInfluence;
|
||||
intensity += ripple;
|
||||
lift = mouseInfluence;
|
||||
}
|
||||
|
||||
if (uUsePageLoadAnimation > 0.5) {
|
||||
float cellRandom = fract(sin(dot(s, vec2(12.9898, 78.233))) * 43758.5453);
|
||||
float cellDelay = cellRandom * 0.8;
|
||||
float cellProgress = clamp((uPageLoadProgress - cellDelay) / 0.2, 0.0, 1.0);
|
||||
float fadeAlpha = smoothstep(0.0, 1.0, cellProgress);
|
||||
intensity *= fadeAlpha;
|
||||
strike = sin(3.14159265 * cellProgress) * step(0.1, intensity);
|
||||
}
|
||||
|
||||
vec4 on0 = step(vec4(0.1), intensity - vec4(0.0, 1.0, 2.0, 4.0) * 0.0625);
|
||||
vec2 on1 = step(vec2(0.1), intensity - vec2(5.0, 8.0) * 0.0625);
|
||||
float level = clamp((intensity - 0.1) / 0.6, 0.0, 1.0);
|
||||
float heat = max(clamp(lift / 3.0, 0.0, 1.0) * uHover, strike);
|
||||
|
||||
vec4 prev0 = texelFetch(uPrev0, texel, 0) * (1.0 - uFresh);
|
||||
vec4 prev1 = texelFetch(uPrev1, texel, 0) * (1.0 - uFresh);
|
||||
vec4 fade0 = max(prev0 * uDecay - 1.0 / 255.0, 0.0);
|
||||
vec4 fade1 = max(prev1 * uDecay - 1.0 / 255.0, 0.0);
|
||||
|
||||
outRings = max(on0, fade0);
|
||||
outExtra = vec4(max(on1, fade1.xy), max(level, fade1.z), max(heat, fade1.w));
|
||||
}`;
|
||||
|
||||
const fontArray = `const uint FONT[${FONT_BITS.length}] = uint[${FONT_BITS.length}](${FONT_BITS.map(
|
||||
bits => `${bits}u`
|
||||
).join(', ')});`;
|
||||
|
||||
const MAIN_FRAGMENT = `#version 300 es
|
||||
precision highp float;
|
||||
precision highp int;
|
||||
|
||||
uniform float iTime;
|
||||
uniform vec3 iResolution;
|
||||
uniform float uScale;
|
||||
uniform vec2 uGridMul;
|
||||
uniform float uDigitSize;
|
||||
uniform float uScanlineIntensity;
|
||||
uniform float uGlitchAmount;
|
||||
uniform float uFlickerAmount;
|
||||
uniform float uChromaticAberration;
|
||||
uniform float uDither;
|
||||
uniform float uCurvature;
|
||||
uniform vec3 uTint;
|
||||
uniform float uBrightness;
|
||||
uniform float uLightMode;
|
||||
uniform sampler2D uRings0;
|
||||
uniform sampler2D uRings1;
|
||||
uniform ivec2 uOrigin;
|
||||
uniform ivec2 uCellCount;
|
||||
uniform int uGlyphs;
|
||||
uniform float uGlow;
|
||||
uniform float uScramble;
|
||||
uniform float uMouseGlow;
|
||||
uniform float uVignette;
|
||||
uniform vec4 uClicks[${MAX_CLICKS}];
|
||||
uniform int uClickMode;
|
||||
uniform float uClickSeconds;
|
||||
uniform float uClock;
|
||||
|
||||
out vec4 outColor;
|
||||
|
||||
${fontArray}
|
||||
|
||||
float time;
|
||||
float clickTear;
|
||||
float clickSplit;
|
||||
float pixelHeat;
|
||||
|
||||
float hash21(vec2 p) {
|
||||
p = fract(p * 234.56);
|
||||
p += dot(p, p + 34.56);
|
||||
return fract(p.x * p.y);
|
||||
}
|
||||
|
||||
float hashCell(vec2 p) {
|
||||
vec3 q = fract(vec3(p.xyx) * 0.1031);
|
||||
q += dot(q, q.yzx + 33.33);
|
||||
return fract((q.x + q.y) * q.z);
|
||||
}
|
||||
|
||||
ivec2 cellTexel(vec2 cell) {
|
||||
return clamp(ivec2(cell) - uOrigin, ivec2(0), uCellCount - 1);
|
||||
}
|
||||
|
||||
float ringValue(float n, vec4 r0, vec4 r1) {
|
||||
if (n < 0.5) return r0.x;
|
||||
if (n < 1.5) return r0.y;
|
||||
if (n < 2.5) return r0.z;
|
||||
if (n < 4.5) return r0.w;
|
||||
if (n < 5.5) return r1.x;
|
||||
return r1.y;
|
||||
}
|
||||
|
||||
float digit(vec2 p) {
|
||||
vec2 grid = uGridMul * 15.0;
|
||||
vec2 cell = floor(p * grid);
|
||||
ivec2 texel = cellTexel(cell);
|
||||
vec4 r0 = texelFetch(uRings0, texel, 0);
|
||||
vec4 r1 = texelFetch(uRings1, texel, 0);
|
||||
float boost = 1.0 + r1.w * uMouseGlow * 1.3;
|
||||
pixelHeat = max(pixelHeat, r1.w);
|
||||
p = fract(p * grid);
|
||||
p *= uDigitSize;
|
||||
|
||||
float px5 = p.x * 5.0;
|
||||
float py5 = (1.0 - p.y) * 5.0;
|
||||
float x = fract(px5);
|
||||
float y = fract(py5);
|
||||
float i = floor(py5) - 2.0;
|
||||
float j = floor(px5) - 2.0;
|
||||
float inside = step(0.0, p.x) * step(p.x, 1.0) * step(0.0, p.y) * step(p.y, 1.0);
|
||||
|
||||
if (uGlyphs == 2) {
|
||||
float rate = 1.2 + r1.w * uScramble * 18.0;
|
||||
float phase = hashCell(cell * 1.37 + 4.1);
|
||||
float epoch = floor(iTime * rate + phase * 7.0);
|
||||
float pick = hashCell(cell + vec2(epoch * 0.731, epoch * 1.913));
|
||||
uint glyph = FONT[int(min(pick * float(FONT.length()), float(FONT.length()) - 1.0))];
|
||||
int bit = int(i + 2.0) * 5 + int(j + 2.0);
|
||||
float lit = float((glyph >> uint(clamp(bit, 0, 24))) & 1u);
|
||||
float glow = max(r0.x, r1.z);
|
||||
float shade = 0.35 + 0.65 * r1.z;
|
||||
return inside * lit * glow * shade * boost * (0.2 + y * 0.8) * (0.75 + x * 0.25);
|
||||
}
|
||||
|
||||
float n = i * i + j * j;
|
||||
float on = ringValue(n, r0, r1);
|
||||
if (uGlyphs == 1) {
|
||||
vec2 d = vec2(x, y) - 0.5;
|
||||
float radius = 0.36 + 0.06 * on;
|
||||
float edge = fwidth(px5) * 0.75;
|
||||
float dot = 1.0 - smoothstep(radius - edge, radius + edge, length(d));
|
||||
return inside * on * dot * boost * (0.55 + 0.45 * (1.0 - length(d) / 0.5));
|
||||
}
|
||||
float brightness = on * (0.2 + y * 0.8) * (0.75 + x * 0.25);
|
||||
return inside * brightness * boost;
|
||||
}
|
||||
|
||||
float onOff(float a, float b, float c) {
|
||||
return step(c, sin(iTime + a * cos(iTime * b))) * uFlickerAmount;
|
||||
}
|
||||
|
||||
float displace(vec2 look) {
|
||||
float y = look.y - mod(iTime * 0.25, 1.0);
|
||||
float window = 1.0 / (1.0 + 50.0 * y * y);
|
||||
return sin(look.y * 20.0 + iTime) * 0.0125 * onOff(4.0, 2.0, 0.8) * (1.0 + cos(iTime * 60.0)) * window;
|
||||
}
|
||||
|
||||
vec2 getLight(vec2 p) {
|
||||
float bar = step(mod(p.y + time * 20.0, 1.0), 0.2) * 0.4 + 1.0;
|
||||
bar *= uScanlineIntensity;
|
||||
|
||||
float displacement = displace(p);
|
||||
p.x += displacement;
|
||||
|
||||
if (uGlitchAmount != 1.0) {
|
||||
float extra = displacement * (uGlitchAmount - 1.0);
|
||||
p.x += extra;
|
||||
}
|
||||
|
||||
p.x += clickTear;
|
||||
|
||||
float middle = digit(p);
|
||||
|
||||
const float off = 0.002;
|
||||
float sum = digit(p + vec2(-off, -off)) + digit(p + vec2(0.0, -off)) + digit(p + vec2(off, -off)) +
|
||||
digit(p + vec2(-off, 0.0)) + digit(p + vec2(0.0, 0.0)) + digit(p + vec2(off, 0.0)) +
|
||||
digit(p + vec2(-off, off)) + digit(p + vec2(0.0, off)) + digit(p + vec2(off, off));
|
||||
|
||||
return vec2(0.9 * middle, sum * 0.1 * bar);
|
||||
}
|
||||
|
||||
float glowAt(vec2 p) {
|
||||
vec2 grid = uGridMul * 15.0;
|
||||
vec2 cell = floor(p * grid);
|
||||
vec2 cellPx = iResolution.xy / (uScale * grid);
|
||||
float sigma = 0.5 * min(cellPx.x, cellPx.y);
|
||||
float center = 0.5 * min(1.0, 1.0 / max(uDigitSize, 0.001));
|
||||
float total = 0.0;
|
||||
for (int oy = -1; oy <= 1; oy++) {
|
||||
for (int ox = -1; ox <= 1; ox++) {
|
||||
vec2 c = cell + vec2(float(ox), float(oy));
|
||||
ivec2 texel = cellTexel(c);
|
||||
vec4 r0 = texelFetch(uRings0, texel, 0);
|
||||
vec4 r1 = texelFetch(uRings1, texel, 0);
|
||||
float emission = uGlyphs == 2
|
||||
? max(r0.x, r1.z) * (0.35 + 0.65 * r1.z) * 0.45
|
||||
: (r0.x + 4.0 * (r0.y + r0.z + r0.w + r1.y) + 8.0 * r1.x) / 25.0;
|
||||
emission *= 1.0 + r1.w * uMouseGlow * 1.6;
|
||||
vec2 d = (p - (c + center) / grid) * iResolution.xy / uScale;
|
||||
total += emission * exp(-dot(d, d) / (2.0 * sigma * sigma));
|
||||
}
|
||||
}
|
||||
return total;
|
||||
}
|
||||
|
||||
vec2 barrel(vec2 uv) {
|
||||
vec2 c = uv * 2.0 - 1.0;
|
||||
float r2 = dot(c, c);
|
||||
c *= 1.0 + uCurvature * r2;
|
||||
return c * 0.5 + 0.5;
|
||||
}
|
||||
|
||||
void main() {
|
||||
time = iTime * 0.333333;
|
||||
vec2 uv = gl_FragCoord.xy / iResolution.xy;
|
||||
|
||||
if (uCurvature != 0.0) {
|
||||
uv = barrel(uv);
|
||||
}
|
||||
|
||||
clickTear = 0.0;
|
||||
clickSplit = 0.0;
|
||||
if (uClickMode > 0) {
|
||||
for (int k = 0; k < ${MAX_CLICKS}; k++) {
|
||||
vec4 click = uClicks[k];
|
||||
if (click.w <= 0.0) continue;
|
||||
float age = uClock - click.z;
|
||||
if (age < 0.0 || age > uClickSeconds) continue;
|
||||
float life = age / uClickSeconds;
|
||||
float envelope = (1.0 - life) * (1.0 - life);
|
||||
if (uClickMode == 1) {
|
||||
float tick = floor(age * 30.0);
|
||||
float bands = 14.0 + 26.0 * hashCell(vec2(click.z, tick * 0.37));
|
||||
float row = floor(uv.y * bands);
|
||||
float pickRow = hashCell(vec2(row + tick * 7.0, click.z * 17.0));
|
||||
float torn = step(0.42, pickRow);
|
||||
float reach = exp(-abs(uv.y - click.y) * 2.5);
|
||||
float shift = (hashCell(vec2(row * 1.7 + tick, click.z)) - 0.5) * 0.22;
|
||||
clickTear += shift * torn * envelope * reach;
|
||||
clickSplit = max(clickSplit, envelope * reach * (0.4 + 0.6 * torn));
|
||||
} else {
|
||||
vec2 aspect = vec2(iResolution.x / iResolution.y, 1.0);
|
||||
vec2 delta = (uv - click.xy) * aspect;
|
||||
float dist = length(delta);
|
||||
float front = age * 1.6;
|
||||
float band = exp(-pow((dist - front) / 0.18, 2.0));
|
||||
float wave = sin((dist - front) * 40.0) * band;
|
||||
uv += delta / aspect * wave * 0.05 * envelope;
|
||||
clickSplit = max(clickSplit, envelope * band);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
vec2 p = uv * uScale;
|
||||
pixelHeat = 0.0;
|
||||
vec2 lightG = getLight(p);
|
||||
float heat = pixelHeat;
|
||||
vec2 lightR = lightG;
|
||||
vec2 lightB = lightG;
|
||||
|
||||
float split = uChromaticAberration + clickSplit * 6.0;
|
||||
if (split != 0.0) {
|
||||
vec2 ca = vec2(split) / iResolution.xy;
|
||||
lightR = getLight(p + ca);
|
||||
lightB = getLight(p - ca);
|
||||
}
|
||||
|
||||
if (uGlow > 0.0) {
|
||||
float bloom = uGlow * 0.2 * glowAt(p);
|
||||
lightR.y += bloom;
|
||||
lightG.y += bloom;
|
||||
lightB.y += bloom;
|
||||
}
|
||||
|
||||
vec3 core = vec3(lightR.x, lightG.x, lightB.x);
|
||||
vec3 halo = vec3(lightR.y, lightG.y, lightB.y);
|
||||
vec3 raw = core + halo;
|
||||
|
||||
vec3 luma = vec3(0.2126, 0.7152, 0.0722);
|
||||
float peak = max(uTint.r, max(uTint.g, uTint.b));
|
||||
float phosphor = clamp(uGlow, 0.0, 1.0);
|
||||
vec3 vividTint = clamp(mix(vec3(dot(uTint, luma)), uTint, 1.0 + 0.8 * phosphor), 0.0, 1.0);
|
||||
vec3 coreTint = mix(uTint, vec3(peak), phosphor * 0.45 * smoothstep(0.45, 0.9, core));
|
||||
vec3 col = core * coreTint + halo * vividTint;
|
||||
col += (vec3(1.0) - uTint) * min(raw, vec3(1.0)) * heat * uMouseGlow * 0.6;
|
||||
col *= uBrightness;
|
||||
|
||||
if (uVignette > 0.0) {
|
||||
float edge = 0.04 + 0.22 * uVignette;
|
||||
vec2 fade = smoothstep(vec2(0.0), vec2(edge), uv) * smoothstep(vec2(0.0), vec2(edge), 1.0 - uv);
|
||||
float mask = fade.x * fade.y;
|
||||
mask = mask * mask * (3.0 - 2.0 * mask);
|
||||
float keep = mix(1.0, mask, clamp(uVignette * 1.5, 0.0, 1.0));
|
||||
col *= keep;
|
||||
core *= keep;
|
||||
halo *= keep;
|
||||
}
|
||||
|
||||
if (uLightMode > 0.5) {
|
||||
vec3 luma = vec3(0.2126, 0.7152, 0.0722);
|
||||
float lum = dot(uTint, luma);
|
||||
float peak = max(uTint.r, max(uTint.g, uTint.b));
|
||||
vec3 hue = uTint / max(peak, 0.0001);
|
||||
vec3 vivid = clamp(mix(vec3(dot(hue, luma)), hue, 1.6), 0.0, 1.0);
|
||||
vivid = clamp(vivid * (0.3 / max(dot(vivid, luma), 0.0001)), 0.0, 1.0);
|
||||
vec3 ink = mix(uTint, vivid, smoothstep(0.3, 0.6, lum));
|
||||
vec3 cover = (core * 1.15 + halo * 0.4) * uBrightness * (1.0 + heat * uMouseGlow * 0.4);
|
||||
if (uDither > 0.0) cover += (hash21(gl_FragCoord.xy) - 0.5) * (uDither * 0.003922);
|
||||
cover = clamp(cover, 0.0, 0.94);
|
||||
float alpha = max(cover.r, max(cover.g, cover.b));
|
||||
outColor = vec4(alpha - cover * (1.0 - ink), alpha);
|
||||
return;
|
||||
}
|
||||
|
||||
if (uDither > 0.0) {
|
||||
float rnd = hash21(gl_FragCoord.xy);
|
||||
col += (rnd - 0.5) * (uDither * 0.003922);
|
||||
}
|
||||
|
||||
col = clamp(col, 0.0, 1.0);
|
||||
outColor = vec4(col, max(col.r, max(col.g, col.b)));
|
||||
}`;
|
||||
|
||||
const clamp = (value, min, max) => Math.min(max, Math.max(min, value));
|
||||
|
||||
const compile = (gl, type, source) => {
|
||||
const shader = gl.createShader(type);
|
||||
if (!shader) return null;
|
||||
gl.shaderSource(shader, source);
|
||||
gl.compileShader(shader);
|
||||
if (gl.getShaderParameter(shader, gl.COMPILE_STATUS)) return shader;
|
||||
gl.deleteShader(shader);
|
||||
return null;
|
||||
};
|
||||
|
||||
const link = (gl, fragmentSource) => {
|
||||
const vertex = compile(gl, gl.VERTEX_SHADER, VERTEX);
|
||||
const fragment = compile(gl, gl.FRAGMENT_SHADER, fragmentSource);
|
||||
const program = gl.createProgram();
|
||||
if (!vertex || !fragment || !program) return null;
|
||||
gl.attachShader(program, vertex);
|
||||
gl.attachShader(program, fragment);
|
||||
gl.linkProgram(program);
|
||||
gl.deleteShader(vertex);
|
||||
gl.deleteShader(fragment);
|
||||
if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
|
||||
gl.deleteProgram(program);
|
||||
return null;
|
||||
}
|
||||
const uniforms = {};
|
||||
const count = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS);
|
||||
for (let i = 0; i < count; i++) {
|
||||
const info = gl.getActiveUniform(program, i);
|
||||
if (!info) continue;
|
||||
const name = info.name.replace(/\[0\]$/, '');
|
||||
uniforms[name] = gl.getUniformLocation(program, name);
|
||||
}
|
||||
return { program, uniforms };
|
||||
};
|
||||
|
||||
const hexToRgb = hex => {
|
||||
let h = String(hex || '#ffffff')
|
||||
.replace('#', '')
|
||||
.trim();
|
||||
if (h.length === 3 || h.length === 4)
|
||||
h = h
|
||||
.slice(0, 3)
|
||||
.split('')
|
||||
.map(c => c + c)
|
||||
.join('');
|
||||
const num = parseInt(h.slice(0, 6), 16);
|
||||
if (Number.isNaN(num)) return [1, 1, 1];
|
||||
return [((num >> 16) & 255) / 255, ((num >> 8) & 255) / 255, (num & 255) / 255];
|
||||
};
|
||||
|
||||
export default function FaultyTerminal({
|
||||
scale = 1,
|
||||
gridMul = [2, 1],
|
||||
digitSize = 1.5,
|
||||
timeScale = 0.3,
|
||||
pause = false,
|
||||
scanlineIntensity = 0.3,
|
||||
glitchAmount = 1,
|
||||
flickerAmount = 1,
|
||||
noiseAmp = 1,
|
||||
chromaticAberration = 0,
|
||||
dither = 0,
|
||||
curvature = 0.2,
|
||||
tint = '#ff5252',
|
||||
mouseReact = true,
|
||||
mouseStrength = 0.2,
|
||||
pageLoadAnimation = true,
|
||||
brightness = 1,
|
||||
glyphs = 'blocks',
|
||||
glow = 0.5,
|
||||
persistence = 0.5,
|
||||
scramble = 0.5,
|
||||
mouseGlow = 0.6,
|
||||
vignette = 0.25,
|
||||
clickEffect = 'glitch',
|
||||
variation = undefined,
|
||||
lightMode = false,
|
||||
dpr = undefined,
|
||||
className = '',
|
||||
style = undefined,
|
||||
...rest
|
||||
}) {
|
||||
const containerRef = useRef(null);
|
||||
const canvasRef = useRef(null);
|
||||
const wakeRef = useRef(null);
|
||||
const settings = {
|
||||
scale: Math.max(0.05, scale),
|
||||
gridX: Math.max(0.1, (gridMul?.[0] ?? 2) * 15),
|
||||
gridY: Math.max(0.1, (gridMul?.[1] ?? 1) * 15),
|
||||
digitSize,
|
||||
timeScale,
|
||||
pause,
|
||||
scanlineIntensity,
|
||||
glitchAmount,
|
||||
flickerAmount,
|
||||
noiseAmp,
|
||||
chromaticAberration,
|
||||
dither: typeof dither === 'boolean' ? (dither ? 1 : 0) : dither,
|
||||
curvature,
|
||||
tint,
|
||||
mouseReact,
|
||||
mouseStrength,
|
||||
pageLoadAnimation,
|
||||
brightness,
|
||||
glyphs: GLYPHS[glyphs] ?? 0,
|
||||
glow: clamp(glow, 0, 3),
|
||||
persistence: clamp(persistence, 0, 1),
|
||||
scramble: clamp(scramble, 0, 1),
|
||||
mouseGlow: clamp(mouseGlow, 0, 1),
|
||||
vignette: clamp(vignette, 0, 1),
|
||||
clickEffect: CLICKS[clickEffect] ?? 0,
|
||||
clickSeconds: CLICK_SECONDS[clickEffect] ?? 1,
|
||||
variation,
|
||||
lightMode,
|
||||
dpr
|
||||
};
|
||||
const settingsRef = useRef(settings);
|
||||
settingsRef.current = settings;
|
||||
|
||||
useEffect(() => {
|
||||
const container = containerRef.current;
|
||||
const canvas = canvasRef.current;
|
||||
const gl = canvas?.getContext('webgl2', {
|
||||
alpha: true,
|
||||
premultipliedAlpha: true,
|
||||
antialias: false,
|
||||
depth: false,
|
||||
stencil: false
|
||||
});
|
||||
if (!container || !canvas || !gl) return undefined;
|
||||
const cellShader = link(gl, CELL_FRAGMENT);
|
||||
const mainShader = link(gl, MAIN_FRAGMENT);
|
||||
if (!cellShader || !mainShader) return undefined;
|
||||
const cu = cellShader.uniforms;
|
||||
const mu = mainShader.uniforms;
|
||||
const vao = gl.createVertexArray();
|
||||
|
||||
const makeTexture = () => {
|
||||
const texture = gl.createTexture();
|
||||
gl.bindTexture(gl.TEXTURE_2D, texture);
|
||||
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
|
||||
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
|
||||
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
|
||||
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
|
||||
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA8, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
|
||||
return texture;
|
||||
};
|
||||
const targets = [0, 1].map(() => {
|
||||
const rings = makeTexture();
|
||||
const extra = makeTexture();
|
||||
const framebuffer = gl.createFramebuffer();
|
||||
gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
|
||||
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, rings, 0);
|
||||
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT1, gl.TEXTURE_2D, extra, 0);
|
||||
return { rings, extra, framebuffer };
|
||||
});
|
||||
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
|
||||
|
||||
const reduce = window.matchMedia?.('(prefers-reduced-motion: reduce)').matches ?? false;
|
||||
const view = { width: 1, height: 1, ratio: 1, columns: 1 };
|
||||
const cells = { x: 0, y: 0, w: 1, h: 1, key: '' };
|
||||
const pointer = { x: 0.5, y: 0.5, inside: false };
|
||||
const mouse = { x: 0.5, y: 0.5 };
|
||||
const clicks = new Float32Array(MAX_CLICKS * 4);
|
||||
let clickIndex = 0;
|
||||
let clock = 0;
|
||||
let hover = 0;
|
||||
let current = 0;
|
||||
let fresh = true;
|
||||
const seedOffset = settingsRef.current.variation;
|
||||
const initialOffset = typeof seedOffset === 'number' ? seedOffset * 10 : Math.random() * 100;
|
||||
let iTime = initialOffset * settingsRef.current.timeScale;
|
||||
let introClock = settingsRef.current.pageLoadAnimation && !reduce ? 0 : 1;
|
||||
let raf = 0;
|
||||
let last = 0;
|
||||
let visible = true;
|
||||
let quiet = 0;
|
||||
|
||||
const layoutCells = s => {
|
||||
const reach = 1 + Math.max(0, s.curvature) * 2;
|
||||
const uvMin = 0.5 - 0.5 * reach;
|
||||
const uvMax = 0.5 + 0.5 * reach;
|
||||
const margin = 0.06 * Math.max(1, Math.abs(s.glitchAmount)) * Math.max(1, Math.abs(s.flickerAmount)) + 0.2;
|
||||
const gridX = s.gridX * view.columns;
|
||||
const x0 = Math.floor((uvMin * s.scale - margin) * gridX) - 2;
|
||||
const x1 = Math.floor((uvMax * s.scale + margin) * gridX) + 2;
|
||||
const y0 = Math.floor((uvMin * s.scale - margin) * s.gridY) - 2;
|
||||
const y1 = Math.floor((uvMax * s.scale + margin) * s.gridY) + 2;
|
||||
const key = `${x0}:${x1}:${y0}:${y1}`;
|
||||
if (key === cells.key) return;
|
||||
cells.key = key;
|
||||
cells.x = x0;
|
||||
cells.y = y0;
|
||||
cells.w = Math.max(1, Math.min(4096, x1 - x0 + 1));
|
||||
cells.h = Math.max(1, Math.min(4096, y1 - y0 + 1));
|
||||
for (const target of targets) {
|
||||
for (const texture of [target.rings, target.extra]) {
|
||||
gl.bindTexture(gl.TEXTURE_2D, texture);
|
||||
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA8, cells.w, cells.h, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
|
||||
}
|
||||
}
|
||||
fresh = true;
|
||||
};
|
||||
|
||||
const stepCells = (s, decay) => {
|
||||
const source = targets[current];
|
||||
const target = targets[1 - current];
|
||||
gl.bindFramebuffer(gl.FRAMEBUFFER, target.framebuffer);
|
||||
gl.drawBuffers([gl.COLOR_ATTACHMENT0, gl.COLOR_ATTACHMENT1]);
|
||||
gl.viewport(0, 0, cells.w, cells.h);
|
||||
gl.disable(gl.BLEND);
|
||||
gl.useProgram(cellShader.program);
|
||||
gl.activeTexture(gl.TEXTURE0);
|
||||
gl.bindTexture(gl.TEXTURE_2D, source.rings);
|
||||
gl.activeTexture(gl.TEXTURE1);
|
||||
gl.bindTexture(gl.TEXTURE_2D, source.extra);
|
||||
gl.uniform1i(cu.uPrev0, 0);
|
||||
gl.uniform1i(cu.uPrev1, 1);
|
||||
gl.uniform1f(cu.iTime, iTime);
|
||||
gl.uniform2f(cu.uGridMul, (s.gridX * view.columns) / 15, s.gridY / 15);
|
||||
gl.uniform1f(cu.uNoiseAmp, s.noiseAmp);
|
||||
gl.uniform1f(cu.uScale, s.scale);
|
||||
gl.uniform2f(cu.uMouse, mouse.x, mouse.y);
|
||||
gl.uniform1f(cu.uMouseStrength, s.mouseStrength);
|
||||
gl.uniform1f(cu.uUseMouse, s.mouseReact ? 1 : 0);
|
||||
gl.uniform1f(cu.uPageLoadProgress, introClock);
|
||||
gl.uniform1f(cu.uUsePageLoadAnimation, s.pageLoadAnimation ? 1 : 0);
|
||||
gl.uniform2i(cu.uOrigin, cells.x, cells.y);
|
||||
gl.uniform1f(cu.uDecay, decay);
|
||||
gl.uniform1f(cu.uFresh, fresh ? 1 : 0);
|
||||
gl.uniform1f(cu.uHover, hover);
|
||||
gl.bindVertexArray(vao);
|
||||
gl.drawArrays(gl.TRIANGLES, 0, 3);
|
||||
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
|
||||
current = 1 - current;
|
||||
fresh = false;
|
||||
};
|
||||
|
||||
const draw = () => {
|
||||
const s = settingsRef.current;
|
||||
const source = targets[current];
|
||||
gl.viewport(0, 0, canvas.width, canvas.height);
|
||||
gl.clearColor(0, 0, 0, 0);
|
||||
gl.clear(gl.COLOR_BUFFER_BIT);
|
||||
gl.useProgram(mainShader.program);
|
||||
gl.activeTexture(gl.TEXTURE0);
|
||||
gl.bindTexture(gl.TEXTURE_2D, source.rings);
|
||||
gl.activeTexture(gl.TEXTURE1);
|
||||
gl.bindTexture(gl.TEXTURE_2D, source.extra);
|
||||
gl.uniform1i(mu.uRings0, 0);
|
||||
gl.uniform1i(mu.uRings1, 1);
|
||||
gl.uniform1f(mu.iTime, iTime);
|
||||
gl.uniform3f(mu.iResolution, canvas.width, canvas.height, canvas.width / canvas.height);
|
||||
gl.uniform1f(mu.uScale, s.scale);
|
||||
gl.uniform2f(mu.uGridMul, (s.gridX * view.columns) / 15, s.gridY / 15);
|
||||
gl.uniform1f(mu.uDigitSize, s.digitSize);
|
||||
gl.uniform1f(mu.uScanlineIntensity, s.scanlineIntensity);
|
||||
gl.uniform1f(mu.uGlitchAmount, reduce ? 0 : s.glitchAmount);
|
||||
gl.uniform1f(mu.uFlickerAmount, reduce ? 0 : s.flickerAmount);
|
||||
gl.uniform1f(mu.uChromaticAberration, s.chromaticAberration);
|
||||
gl.uniform1f(mu.uDither, s.dither);
|
||||
gl.uniform1f(mu.uCurvature, s.curvature);
|
||||
gl.uniform3fv(mu.uTint, hexToRgb(s.tint));
|
||||
gl.uniform1f(mu.uBrightness, s.brightness);
|
||||
gl.uniform1f(mu.uLightMode, s.lightMode ? 1 : 0);
|
||||
gl.uniform2i(mu.uOrigin, cells.x, cells.y);
|
||||
gl.uniform2i(mu.uCellCount, cells.w, cells.h);
|
||||
gl.uniform1i(mu.uGlyphs, s.glyphs);
|
||||
gl.uniform1f(mu.uGlow, s.glow);
|
||||
gl.uniform1f(mu.uScramble, s.scramble);
|
||||
gl.uniform1f(mu.uMouseGlow, s.mouseGlow);
|
||||
gl.uniform1f(mu.uVignette, s.vignette);
|
||||
gl.uniform4fv(mu.uClicks, clicks);
|
||||
gl.uniform1i(mu.uClickMode, s.clickEffect);
|
||||
gl.uniform1f(mu.uClickSeconds, s.clickSeconds);
|
||||
gl.uniform1f(mu.uClock, clock);
|
||||
gl.bindVertexArray(vao);
|
||||
gl.drawArrays(gl.TRIANGLES, 0, 3);
|
||||
gl.bindVertexArray(null);
|
||||
};
|
||||
|
||||
const resize = () => {
|
||||
const s = settingsRef.current;
|
||||
view.width = Math.max(1, container.clientWidth);
|
||||
view.height = Math.max(1, container.clientHeight);
|
||||
view.ratio = Math.min(s.dpr || window.devicePixelRatio || 1, 2);
|
||||
view.columns = Math.min(1, view.width / view.height / 1.5);
|
||||
canvas.width = Math.max(1, Math.round(view.width * view.ratio));
|
||||
canvas.height = Math.max(1, Math.round(view.height * view.ratio));
|
||||
layoutCells(s);
|
||||
stepCells(s, 0);
|
||||
draw();
|
||||
wake();
|
||||
};
|
||||
|
||||
const frame = now => {
|
||||
raf = 0;
|
||||
if (!visible || document.hidden) return;
|
||||
const s = settingsRef.current;
|
||||
const dt = last ? clamp((now - last) / 1000, 0.001, 1 / 20) : 1 / 60;
|
||||
last = now;
|
||||
clock += dt;
|
||||
if (!s.pause && !reduce) iTime += dt * s.timeScale;
|
||||
const targetX = pointer.inside ? pointer.x : 0.5;
|
||||
const targetY = pointer.inside ? pointer.y : 0.5;
|
||||
const follow = 1 - Math.exp(-dt / (pointer.inside ? 0.19988 : 0.6));
|
||||
mouse.x += (targetX - mouse.x) * follow;
|
||||
mouse.y += (targetY - mouse.y) * follow;
|
||||
hover += ((pointer.inside ? 1 : 0) - hover) * (1 - Math.exp(-dt / 0.35));
|
||||
for (let k = 0; k < MAX_CLICKS; k++) {
|
||||
if (clicks[k * 4 + 3] > 0 && clock - clicks[k * 4 + 2] > s.clickSeconds) clicks[k * 4 + 3] = 0;
|
||||
}
|
||||
layoutCells(s);
|
||||
const decay = s.persistence > 0 ? Math.exp(-dt / (0.08 + s.persistence * 1.4)) : 0;
|
||||
stepCells(s, decay);
|
||||
draw();
|
||||
if (introClock < 1) introClock = Math.min(1, introClock + dt / INTRO_SECONDS);
|
||||
let busy = !(s.pause || reduce) || introClock < 1;
|
||||
busy = busy || Math.abs(targetX - mouse.x) + Math.abs(targetY - mouse.y) > 0.0001;
|
||||
busy = busy || Math.abs((pointer.inside ? 1 : 0) - hover) > 0.001;
|
||||
for (let k = 0; k < MAX_CLICKS; k++) busy = busy || clicks[k * 4 + 3] > 0;
|
||||
quiet = busy ? 0 : quiet + dt;
|
||||
if (quiet < 2.5) raf = requestAnimationFrame(frame);
|
||||
};
|
||||
|
||||
function wake() {
|
||||
quiet = 0;
|
||||
if (!raf && visible && !document.hidden) {
|
||||
last = 0;
|
||||
raf = requestAnimationFrame(frame);
|
||||
}
|
||||
}
|
||||
|
||||
const locate = event => {
|
||||
const rect = container.getBoundingClientRect();
|
||||
const x = (event.clientX - rect.left) / Math.max(rect.width, 1);
|
||||
const y = 1 - (event.clientY - rect.top) / Math.max(rect.height, 1);
|
||||
return { x, y, inside: x >= 0 && x <= 1 && y >= 0 && y <= 1 };
|
||||
};
|
||||
|
||||
const onPointerMove = event => {
|
||||
const { x, y, inside } = locate(event);
|
||||
const was = pointer.inside;
|
||||
pointer.inside = inside;
|
||||
if (inside) {
|
||||
pointer.x = x;
|
||||
pointer.y = y;
|
||||
}
|
||||
if (inside || was) wake();
|
||||
};
|
||||
|
||||
const onPointerDown = event => {
|
||||
const s = settingsRef.current;
|
||||
const { x, y, inside } = locate(event);
|
||||
if (!inside || reduce || !s.clickEffect) return;
|
||||
const o = clickIndex * 4;
|
||||
clicks[o] = x;
|
||||
clicks[o + 1] = y;
|
||||
clicks[o + 2] = clock;
|
||||
clicks[o + 3] = 1;
|
||||
clickIndex = (clickIndex + 1) % MAX_CLICKS;
|
||||
wake();
|
||||
};
|
||||
|
||||
const onPointerLeave = () => {
|
||||
pointer.inside = false;
|
||||
wake();
|
||||
};
|
||||
|
||||
const onVisibility = () => wake();
|
||||
|
||||
const resizeObserver = new ResizeObserver(resize);
|
||||
resizeObserver.observe(container);
|
||||
const intersection = new IntersectionObserver(entries => {
|
||||
visible = entries.some(entry => entry.isIntersecting);
|
||||
if (visible) wake();
|
||||
});
|
||||
intersection.observe(container);
|
||||
window.addEventListener('pointermove', onPointerMove, { passive: true });
|
||||
window.addEventListener('pointerdown', onPointerDown, { passive: true });
|
||||
document.documentElement.addEventListener('pointerleave', onPointerLeave);
|
||||
document.addEventListener('visibilitychange', onVisibility);
|
||||
resize();
|
||||
wakeRef.current = wake;
|
||||
|
||||
return () => {
|
||||
cancelAnimationFrame(raf);
|
||||
wakeRef.current = null;
|
||||
resizeObserver.disconnect();
|
||||
intersection.disconnect();
|
||||
window.removeEventListener('pointermove', onPointerMove);
|
||||
window.removeEventListener('pointerdown', onPointerDown);
|
||||
document.documentElement.removeEventListener('pointerleave', onPointerLeave);
|
||||
document.removeEventListener('visibilitychange', onVisibility);
|
||||
for (const target of targets) {
|
||||
gl.deleteTexture(target.rings);
|
||||
gl.deleteTexture(target.extra);
|
||||
gl.deleteFramebuffer(target.framebuffer);
|
||||
}
|
||||
gl.deleteVertexArray(vao);
|
||||
gl.deleteProgram(cellShader.program);
|
||||
gl.deleteProgram(mainShader.program);
|
||||
gl.getExtension('WEBGL_lose_context')?.loseContext();
|
||||
};
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
wakeRef.current?.();
|
||||
});
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={containerRef}
|
||||
className={`relative h-full w-full overflow-hidden${className ? ` ${className}` : ''}`}
|
||||
style={style}
|
||||
{...rest}
|
||||
>
|
||||
<canvas ref={canvasRef} className="absolute inset-0 block h-full w-full" aria-hidden="true" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import { lazy, Suspense } from "react";
|
||||
|
||||
const FaultyTerminal = lazy(() => import("./FaultyTerminal.js"));
|
||||
|
||||
export const FaultyTerminalBackdrop = () => (
|
||||
<div aria-hidden="true" className="pointer-events-none fixed inset-0 z-0 opacity-60">
|
||||
<Suspense fallback={null}>
|
||||
<FaultyTerminal
|
||||
tint="#ff5252"
|
||||
glyphs="blocks"
|
||||
brightness={0.7}
|
||||
glow={0.5}
|
||||
vignette={0.28}
|
||||
scanlineIntensity={0.25}
|
||||
persistence={0.4}
|
||||
mouseReact={false}
|
||||
/>
|
||||
</Suspense>
|
||||
</div>
|
||||
);
|
||||
@@ -0,0 +1,175 @@
|
||||
import type { ImgHTMLAttributes } from "react";
|
||||
|
||||
type IconProps = Omit<ImgHTMLAttributes<HTMLImageElement>, "src" | "alt"> & {
|
||||
filled?: boolean;
|
||||
};
|
||||
|
||||
const ImgIcon = ({
|
||||
src,
|
||||
className = "",
|
||||
...props
|
||||
}: { src: string } & IconProps) => (
|
||||
<img
|
||||
src={src}
|
||||
alt=""
|
||||
aria-hidden="true"
|
||||
className={`inline-block h-4 w-4 object-contain ${className}`}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
|
||||
export const FolderIcon = (props: IconProps) => (
|
||||
<ImgIcon src="/icons/folder.webp" {...props} />
|
||||
);
|
||||
|
||||
export const FileIcon = (props: IconProps) => (
|
||||
<ImgIcon src="/icons/document.webp" {...props} />
|
||||
);
|
||||
|
||||
export const ImageIcon = (props: IconProps) => (
|
||||
<ImgIcon src="/icons/picture.webp" {...props} />
|
||||
);
|
||||
|
||||
export const PlayIcon = (props: IconProps) => (
|
||||
<ImgIcon src="/icons/file.webp" {...props} />
|
||||
);
|
||||
|
||||
export const AudioIcon = (props: IconProps) => (
|
||||
<ImgIcon src="/icons/activity.webp" {...props} />
|
||||
);
|
||||
|
||||
export const ArchiveIcon = (props: IconProps) => (
|
||||
<ImgIcon src="/icons/folder.webp" {...props} />
|
||||
);
|
||||
|
||||
export const UploadIcon = (props: IconProps) => (
|
||||
<ImgIcon src="/icons/upload.webp" {...props} />
|
||||
);
|
||||
|
||||
export const DownloadIcon = (props: IconProps) => (
|
||||
<ImgIcon src="/icons/download.webp" {...props} />
|
||||
);
|
||||
|
||||
export const PlusIcon = (props: IconProps) => (
|
||||
<ImgIcon src="/icons/plus.webp" {...props} />
|
||||
);
|
||||
|
||||
export const TrashIcon = (props: IconProps) => (
|
||||
<ImgIcon src="/icons/trash-can.webp" {...props} />
|
||||
);
|
||||
|
||||
export const TrashEmptyIcon = (props: IconProps) => (
|
||||
<ImgIcon src="/icons/trash-empty.webp" {...props} />
|
||||
);
|
||||
|
||||
export const RestoreIcon = (props: IconProps) => (
|
||||
<ImgIcon src="/icons/restore-data.webp" {...props} />
|
||||
);
|
||||
|
||||
export const RefreshIcon = (props: IconProps) => (
|
||||
<ImgIcon src="/icons/synchronize.webp" {...props} />
|
||||
);
|
||||
|
||||
export const StarIcon = (props: IconProps) => (
|
||||
<ImgIcon src="/icons/favorite.webp" {...props} />
|
||||
);
|
||||
|
||||
export const SearchIcon = (props: IconProps) => (
|
||||
<ImgIcon src="/icons/search.webp" {...props} />
|
||||
);
|
||||
|
||||
export const UsersIcon = (props: IconProps) => (
|
||||
<ImgIcon src="/icons/accounts.webp" {...props} />
|
||||
);
|
||||
|
||||
export const SettingsIcon = (props: IconProps) => (
|
||||
<ImgIcon src="/icons/personal-settings.webp" {...props} />
|
||||
);
|
||||
|
||||
export const LogoutIcon = (props: IconProps) => (
|
||||
<ImgIcon src="/icons/sign-out.webp" {...props} />
|
||||
);
|
||||
|
||||
export const ShieldIcon = (props: IconProps) => (
|
||||
<ImgIcon src="/icons/accounts.webp" {...props} />
|
||||
);
|
||||
|
||||
export const HardDriveIcon = (props: IconProps) => (
|
||||
<ImgIcon src="/icons/storage.webp" {...props} />
|
||||
);
|
||||
|
||||
export const ActivityIcon = (props: IconProps) => (
|
||||
<ImgIcon src="/icons/activity.webp" {...props} />
|
||||
);
|
||||
|
||||
export const SearchNavIcon = (props: IconProps) => (
|
||||
<ImgIcon src="/icons/search.webp" {...props} />
|
||||
);
|
||||
|
||||
export const FilterIcon = (props: IconProps) => (
|
||||
<ImgIcon src="/icons/filter.webp" {...props} />
|
||||
);
|
||||
|
||||
export const ShareIcon = (props: IconProps) => (
|
||||
<ImgIcon src="/icons/share.webp" {...props} />
|
||||
);
|
||||
|
||||
export const MenuIcon = (props: IconProps) => (
|
||||
<ImgIcon src="/icons/menu.webp" {...props} />
|
||||
);
|
||||
|
||||
export const CloseIcon = (props: IconProps) => (
|
||||
<ImgIcon src="/icons/close.webp" {...props} />
|
||||
);
|
||||
|
||||
export const ArrowLeftIcon = (props: IconProps) => (
|
||||
<ImgIcon src="/icons/back.webp" {...props} />
|
||||
);
|
||||
|
||||
export const ArrowRightIcon = (props: IconProps) => (
|
||||
<ImgIcon
|
||||
src="/icons/back.webp"
|
||||
{...props}
|
||||
style={{ transform: "rotate(180deg)", ...((props.style as any) || {}) }}
|
||||
/>
|
||||
);
|
||||
|
||||
export const PenIcon = (props: IconProps) => (
|
||||
<ImgIcon src="/icons/edit-pencil.webp" {...props} />
|
||||
);
|
||||
|
||||
export const PinIcon = (props: IconProps) => (
|
||||
<ImgIcon src="/icons/pin.webp" {...props} />
|
||||
);
|
||||
|
||||
export const MoveIcon = (props: IconProps) => (
|
||||
<ImgIcon src="/icons/move.webp" {...props} />
|
||||
);
|
||||
|
||||
export const ChatIcon = (props: IconProps) => (
|
||||
<ImgIcon src="/icons/speech-bubble.webp" {...props} />
|
||||
);
|
||||
|
||||
export const SendIcon = (props: IconProps) => (
|
||||
<ImgIcon src="/icons/send.webp" {...props} />
|
||||
);
|
||||
|
||||
export const ClearIcon = (props: IconProps) => (
|
||||
<ImgIcon src="/icons/clear.webp" {...props} />
|
||||
);
|
||||
|
||||
export const SaveIcon = (props: IconProps) => (
|
||||
<ImgIcon src="/icons/save.webp" {...props} />
|
||||
);
|
||||
|
||||
export const OpenedFolderIcon = (props: IconProps) => (
|
||||
<ImgIcon src="/icons/opened-folder.webp" {...props} />
|
||||
);
|
||||
|
||||
export const DeactivateIcon = (props: IconProps) => (
|
||||
<ImgIcon src="/icons/deactivate.webp" {...props} />
|
||||
);
|
||||
|
||||
export const PasswordResetIcon = (props: IconProps) => (
|
||||
<ImgIcon src="/icons/password-reset.webp" {...props} />
|
||||
);
|
||||
@@ -0,0 +1,244 @@
|
||||
export interface User {
|
||||
id: string;
|
||||
email: string;
|
||||
first_name: string;
|
||||
last_name: string;
|
||||
must_change_password: boolean;
|
||||
}
|
||||
|
||||
export interface Country {
|
||||
id: number;
|
||||
code: string;
|
||||
name: string;
|
||||
phone_code: string | null;
|
||||
}
|
||||
|
||||
export interface Organization {
|
||||
id: string;
|
||||
name: string;
|
||||
slug: string;
|
||||
website: string | null;
|
||||
industry: string | null;
|
||||
phone: string | null;
|
||||
email: string | null;
|
||||
address_line1: string | null;
|
||||
address_line2: string | null;
|
||||
postal_code: string | null;
|
||||
city: string | null;
|
||||
country_id: number | null;
|
||||
country_name: string | null;
|
||||
country_code: string | null;
|
||||
description: string | null;
|
||||
owner_id: string | null;
|
||||
owner_name: string | null;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
}
|
||||
|
||||
export interface Contact {
|
||||
id: string;
|
||||
first_name: string;
|
||||
last_name: string;
|
||||
organization_id: string | null;
|
||||
organization_name: string | null;
|
||||
email: string | null;
|
||||
phone: string | null;
|
||||
mobile: string | null;
|
||||
job_title: string | null;
|
||||
country_id: number | null;
|
||||
country_name: string | null;
|
||||
country_code: string | null;
|
||||
external_source: string | null;
|
||||
external_id: string | null;
|
||||
description: string | null;
|
||||
owner_id: string | null;
|
||||
owner_name: string | null;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
}
|
||||
|
||||
/** Corps accepte par les routes creation / mise a jour d'entreprise. */
|
||||
export type OrganizationInput = {
|
||||
name?: string;
|
||||
website?: string | null;
|
||||
industry?: string | null;
|
||||
phone?: string | null;
|
||||
email?: string | null;
|
||||
addressLine1?: string | null;
|
||||
addressLine2?: string | null;
|
||||
postalCode?: string | null;
|
||||
city?: string | null;
|
||||
countryId?: number | null;
|
||||
description?: string | null;
|
||||
};
|
||||
|
||||
/** Corps accepte par les routes creation / mise a jour de prospect. */
|
||||
export type ContactInput = {
|
||||
firstName?: string;
|
||||
lastName?: string;
|
||||
organizationId?: string | null;
|
||||
email?: string | null;
|
||||
phone?: string | null;
|
||||
mobile?: string | null;
|
||||
jobTitle?: string | null;
|
||||
countryId?: number | null;
|
||||
externalSource?: string | null;
|
||||
externalId?: string | null;
|
||||
description?: string | null;
|
||||
};
|
||||
|
||||
/** Pagination renvoyee par les listes, sans type : la donnee est homogene. */
|
||||
export interface Pagination {
|
||||
total: number;
|
||||
page: number;
|
||||
limit: number;
|
||||
}
|
||||
|
||||
export class ApiError extends Error {
|
||||
readonly status: number;
|
||||
|
||||
constructor(status: number, message: string) {
|
||||
super(message);
|
||||
this.name = "ApiError";
|
||||
this.status = status;
|
||||
}
|
||||
}
|
||||
|
||||
const BASE = "/api/crm";
|
||||
|
||||
/**
|
||||
* Un seul point d'entree HTTP. Le cookie de session est envoye
|
||||
* automatiquement (same-origin), et toute erreur non-2xx devient une
|
||||
* ApiError portant le message serveur, jamais un corps brut.
|
||||
*/
|
||||
const request = async <T>(path: string, init?: RequestInit): Promise<T> => {
|
||||
let response: Response;
|
||||
try {
|
||||
response = await fetch(`${BASE}${path}`, {
|
||||
credentials: "same-origin",
|
||||
...init,
|
||||
headers: {
|
||||
...(init?.body ? { "content-type": "application/json" } : {}),
|
||||
...init?.headers,
|
||||
},
|
||||
});
|
||||
} catch {
|
||||
throw new ApiError(0, "Serveur injoignable. Verifiez votre connexion.");
|
||||
}
|
||||
|
||||
const body: unknown = await response.json().catch(() => null);
|
||||
if (!response.ok) {
|
||||
const message =
|
||||
(body as { error?: { message?: string } } | null)?.error?.message ??
|
||||
"Une erreur est survenue.";
|
||||
throw new ApiError(response.status, message);
|
||||
}
|
||||
return body as T;
|
||||
};
|
||||
|
||||
export const api = {
|
||||
me: () => request<{ user: User }>("/auth/me"),
|
||||
|
||||
login: (email: string, password: string) =>
|
||||
request<{ user: User }>("/auth/login", {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ email, password }),
|
||||
}),
|
||||
|
||||
logout: () => request<{ ok: boolean }>("/auth/logout", { method: "POST" }),
|
||||
|
||||
changePassword: (current: string, next: string) =>
|
||||
request<{ ok: boolean }>("/auth/change-password", {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ current, next }),
|
||||
}),
|
||||
|
||||
countries: (search?: string) =>
|
||||
request<{ countries: Country[] }>(
|
||||
`/countries${search ? `?q=${encodeURIComponent(search)}` : ""}`,
|
||||
),
|
||||
|
||||
createCountry: (input: { code: string; name: string; phoneCode?: string | null }) =>
|
||||
request<{ country: Country }>("/countries", {
|
||||
method: "POST",
|
||||
body: JSON.stringify(input),
|
||||
}),
|
||||
|
||||
updateCountry: (id: number, input: { code?: string; name?: string; phoneCode?: string | null }) =>
|
||||
request<{ country: Country }>(`/countries/${id}`, {
|
||||
method: "PATCH",
|
||||
body: JSON.stringify(input),
|
||||
}),
|
||||
|
||||
deleteCountry: (id: number) =>
|
||||
request<{ ok: boolean }>(`/countries/${id}`, { method: "DELETE" }),
|
||||
|
||||
organizations: (search?: string, page = 1, limit = 25) => {
|
||||
const params = new URLSearchParams({ page: String(page), limit: String(limit) });
|
||||
if (search) params.set("q", search);
|
||||
return request<{ organizations: Organization[] } & Pagination>(
|
||||
`/organizations?${params.toString()}`,
|
||||
);
|
||||
},
|
||||
|
||||
organization: (id: string) =>
|
||||
request<{ organization: Organization }>(`/organizations/${encodeURIComponent(id)}`),
|
||||
|
||||
createOrganization: (input: OrganizationInput) =>
|
||||
request<{ organization: Organization }>("/organizations", {
|
||||
method: "POST",
|
||||
body: JSON.stringify(input),
|
||||
}),
|
||||
|
||||
updateOrganization: (id: string, input: OrganizationInput) =>
|
||||
request<{ organization: Organization }>(`/organizations/${encodeURIComponent(id)}`, {
|
||||
method: "PATCH",
|
||||
body: JSON.stringify(input),
|
||||
}),
|
||||
|
||||
deleteOrganization: (id: string) =>
|
||||
request<{ ok: boolean }>(`/organizations/${encodeURIComponent(id)}`, { method: "DELETE" }),
|
||||
|
||||
contacts: (options: {
|
||||
search?: string | undefined;
|
||||
organizationId?: string | undefined;
|
||||
page?: number | undefined;
|
||||
limit?: number | undefined;
|
||||
} = {}) => {
|
||||
const params = new URLSearchParams({
|
||||
page: String(options.page ?? 1),
|
||||
limit: String(options.limit ?? 25),
|
||||
});
|
||||
if (options.search) params.set("q", options.search);
|
||||
if (options.organizationId) params.set("organizationId", options.organizationId);
|
||||
return request<{ contacts: Contact[] } & Pagination>(
|
||||
`/contacts?${params.toString()}`,
|
||||
);
|
||||
},
|
||||
|
||||
contact: (id: string) =>
|
||||
request<{ contact: Contact }>(`/contacts/${encodeURIComponent(id)}`),
|
||||
|
||||
createContact: (input: ContactInput) =>
|
||||
request<{ contact: Contact }>("/contacts", {
|
||||
method: "POST",
|
||||
body: JSON.stringify(input),
|
||||
}),
|
||||
|
||||
updateContact: (id: string, input: ContactInput) =>
|
||||
request<{ contact: Contact }>(`/contacts/${encodeURIComponent(id)}`, {
|
||||
method: "PATCH",
|
||||
body: JSON.stringify(input),
|
||||
}),
|
||||
|
||||
deleteContact: (id: string) =>
|
||||
request<{ ok: boolean }>(`/contacts/${encodeURIComponent(id)}`, { method: "DELETE" }),
|
||||
};
|
||||
|
||||
/** Date ISO en date lisible, sans changer de jour a cause du fuseau. */
|
||||
export const formatDate = (iso: string): string =>
|
||||
new Date(iso).toLocaleDateString("fr-FR", {
|
||||
day: "2-digit",
|
||||
month: "2-digit",
|
||||
year: "numeric",
|
||||
});
|
||||
@@ -0,0 +1,16 @@
|
||||
import { StrictMode } from "react";
|
||||
import { createRoot } from "react-dom/client";
|
||||
import { App } from "./App.js";
|
||||
import "./styles/index.css";
|
||||
|
||||
const container = document.getElementById("root");
|
||||
|
||||
if (!container) {
|
||||
throw new Error("Element racine introuvable");
|
||||
}
|
||||
|
||||
createRoot(container).render(
|
||||
<StrictMode>
|
||||
<App />
|
||||
</StrictMode>,
|
||||
);
|
||||
@@ -0,0 +1,109 @@
|
||||
import { useState, type FormEvent } from "react";
|
||||
import { Button, Card, CardContent, CardDescription, CardHeader, CardTitle, Input } from "@cohaise/ui";
|
||||
import { ApiError, api, type User } from "../lib/api.js";
|
||||
|
||||
interface Props {
|
||||
user: User;
|
||||
onCompleted: () => void;
|
||||
onLogout: () => void;
|
||||
}
|
||||
|
||||
export const ChangePassword = ({ user, onCompleted, onLogout }: Props) => {
|
||||
const [current, setCurrent] = useState("");
|
||||
const [next, setNext] = useState("");
|
||||
const [confirm, setConfirm] = useState("");
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
const submit = async (event: FormEvent<HTMLFormElement>) => {
|
||||
event.preventDefault();
|
||||
|
||||
if (next !== confirm) {
|
||||
setError("Les deux mots de passe ne correspondent pas.");
|
||||
return;
|
||||
}
|
||||
if (next.length < 8) {
|
||||
setError("Le nouveau mot de passe doit contenir au moins 8 caractères.");
|
||||
return;
|
||||
}
|
||||
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
try {
|
||||
await api.changePassword(current, next);
|
||||
onCompleted();
|
||||
} catch (caught) {
|
||||
setError(caught instanceof ApiError ? caught.message : "Modification impossible.");
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<main className="flex min-h-dvh items-center justify-center bg-background px-4 py-10">
|
||||
<div className="w-full max-w-sm">
|
||||
<header className="mb-6 text-center">
|
||||
<p className="font-display text-xs font-semibold uppercase tracking-logo text-accent">
|
||||
CoHaiSe
|
||||
</p>
|
||||
<h1 className="font-display mt-2 text-lg font-semibold uppercase tracking-label text-foreground">
|
||||
Nouveau mot de passe
|
||||
</h1>
|
||||
<p className="mt-2 text-sm leading-relaxed text-muted-foreground">
|
||||
Bienvenue {user.first_name}. Ce mot de passe a été défini par un
|
||||
administrateur : choisissez le vôtre.
|
||||
</p>
|
||||
</header>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Changement requis</CardTitle>
|
||||
<CardDescription>
|
||||
Les autres sessions ouvertes sur ce compte seront fermées.
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<form className="flex flex-col gap-4" onSubmit={(event) => void submit(event)}>
|
||||
<Input
|
||||
label="Mot de passe actuel"
|
||||
type="password"
|
||||
autoComplete="current-password"
|
||||
required
|
||||
autoFocus
|
||||
value={current}
|
||||
onChange={(event) => setCurrent(event.target.value)}
|
||||
/>
|
||||
<Input
|
||||
label="Nouveau mot de passe"
|
||||
type="password"
|
||||
autoComplete="new-password"
|
||||
required
|
||||
minLength={8}
|
||||
hint="8 caractères minimum."
|
||||
value={next}
|
||||
onChange={(event) => setNext(event.target.value)}
|
||||
/>
|
||||
<Input
|
||||
label="Confirmation"
|
||||
type="password"
|
||||
autoComplete="new-password"
|
||||
required
|
||||
minLength={8}
|
||||
value={confirm}
|
||||
onChange={(event) => setConfirm(event.target.value)}
|
||||
{...(error ? { error } : {})}
|
||||
/>
|
||||
|
||||
<Button type="submit" size="lg" fullWidth isLoading={busy}>
|
||||
Enregistrer
|
||||
</Button>
|
||||
<Button type="button" variant="ghost" size="md" fullWidth onClick={onLogout}>
|
||||
Se déconnecter
|
||||
</Button>
|
||||
</form>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
</main>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,339 @@
|
||||
import { useCallback, useEffect, useState, type FormEvent } from "react";
|
||||
import { Button, Card, CardContent, CardHeader, CardTitle, Input, Skeleton } from "@cohaise/ui";
|
||||
import {
|
||||
ApiError,
|
||||
api,
|
||||
formatDate,
|
||||
type Contact,
|
||||
type ContactInput,
|
||||
type Country,
|
||||
type Organization,
|
||||
} from "../lib/api.js";
|
||||
|
||||
const EMPTY: ContactInput = {
|
||||
firstName: "",
|
||||
lastName: "",
|
||||
organizationId: null,
|
||||
email: null,
|
||||
phone: null,
|
||||
mobile: null,
|
||||
jobTitle: null,
|
||||
countryId: null,
|
||||
description: null,
|
||||
};
|
||||
|
||||
const text = (value: string): string | null => (value.trim() ? value.trim() : null);
|
||||
|
||||
export const Contacts = () => {
|
||||
const [rows, setRows] = useState<Contact[]>([]);
|
||||
const [organizations, setOrganizations] = useState<Organization[]>([]);
|
||||
const [countries, setCountries] = useState<Country[]>([]);
|
||||
const [total, setTotal] = useState(0);
|
||||
const [search, setSearch] = useState("");
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [editing, setEditing] = useState<Contact | null>(null);
|
||||
const [form, setForm] = useState<ContactInput>(EMPTY);
|
||||
const [open, setOpen] = useState(false);
|
||||
|
||||
const load = useCallback(async () => {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
const result = await api.contacts({ search: search || undefined });
|
||||
setRows(result.contacts);
|
||||
setTotal(result.total);
|
||||
} catch (caught) {
|
||||
setError(caught instanceof ApiError ? caught.message : "Chargement impossible.");
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [search]);
|
||||
|
||||
useEffect(() => {
|
||||
void load();
|
||||
}, [load]);
|
||||
|
||||
// Les listes deroulantes sont des donnees de reference : leur echec ne doit
|
||||
// pas empecher l'ecran de s'afficher, on les laisse vides.
|
||||
useEffect(() => {
|
||||
void api
|
||||
.countries()
|
||||
.then((result) => setCountries(result.countries))
|
||||
.catch(() => undefined);
|
||||
void api
|
||||
.organizations(undefined, 1, 100)
|
||||
.then((result) => setOrganizations(result.organizations))
|
||||
.catch(() => undefined);
|
||||
}, []);
|
||||
|
||||
const openCreate = () => {
|
||||
setEditing(null);
|
||||
setForm(EMPTY);
|
||||
setError(null);
|
||||
setOpen(true);
|
||||
};
|
||||
|
||||
const openEdit = (contact: Contact) => {
|
||||
setOpen(true);
|
||||
setEditing(contact);
|
||||
setForm({
|
||||
firstName: contact.first_name,
|
||||
lastName: contact.last_name,
|
||||
organizationId: contact.organization_id,
|
||||
email: contact.email,
|
||||
phone: contact.phone,
|
||||
mobile: contact.mobile,
|
||||
jobTitle: contact.job_title,
|
||||
countryId: contact.country_id,
|
||||
description: contact.description,
|
||||
});
|
||||
setError(null);
|
||||
};
|
||||
|
||||
const close = () => {
|
||||
setEditing(null);
|
||||
setForm(EMPTY);
|
||||
setError(null);
|
||||
setOpen(false);
|
||||
};
|
||||
|
||||
const submit = async (event: FormEvent<HTMLFormElement>) => {
|
||||
event.preventDefault();
|
||||
const firstName = text(form.firstName ?? "");
|
||||
const lastName = text(form.lastName ?? "");
|
||||
if (!firstName || !lastName) {
|
||||
setError("Le prénom et le nom sont obligatoires.");
|
||||
return;
|
||||
}
|
||||
|
||||
const payload: ContactInput = {
|
||||
firstName,
|
||||
lastName,
|
||||
organizationId: form.organizationId ?? null,
|
||||
email: text(form.email ?? ""),
|
||||
phone: text(form.phone ?? ""),
|
||||
mobile: text(form.mobile ?? ""),
|
||||
jobTitle: text(form.jobTitle ?? ""),
|
||||
countryId: form.countryId ?? null,
|
||||
description: text(form.description ?? ""),
|
||||
};
|
||||
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
try {
|
||||
if (editing) await api.updateContact(editing.id, payload);
|
||||
else await api.createContact(payload);
|
||||
close();
|
||||
await load();
|
||||
} catch (caught) {
|
||||
setError(caught instanceof ApiError ? caught.message : "Enregistrement impossible.");
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
const remove = async (contact: Contact) => {
|
||||
const label = `${contact.first_name} ${contact.last_name}`;
|
||||
if (!window.confirm(`Supprimer « ${label} » ?`)) return;
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
try {
|
||||
await api.deleteContact(contact.id);
|
||||
await load();
|
||||
} catch (caught) {
|
||||
setError(caught instanceof ApiError ? caught.message : "Suppression impossible.");
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
const set = (key: keyof ContactInput) => (value: string | number | null) => {
|
||||
setForm((current) => ({
|
||||
...current,
|
||||
[key]: key === "countryId" ? (value === null ? null : Number(value)) : text(String(value ?? "")),
|
||||
}));
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex min-h-0 flex-1 flex-col gap-6">
|
||||
<div className="flex flex-wrap items-end justify-between gap-4">
|
||||
<div className="w-full max-w-xs">
|
||||
<Input
|
||||
label="Rechercher"
|
||||
type="search"
|
||||
placeholder="Prénom, nom, e-mail, entreprise…"
|
||||
value={search}
|
||||
onChange={(event) => setSearch(event.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<Button onClick={openCreate}>Nouveau prospect</Button>
|
||||
</div>
|
||||
|
||||
{open ? (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>{editing ? "Modifier le prospect" : "Nouveau prospect"}</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<form className="grid gap-4 sm:grid-cols-2" onSubmit={(event) => void submit(event)}>
|
||||
<Input
|
||||
label="Prénom *"
|
||||
required
|
||||
value={form.firstName ?? ""}
|
||||
onChange={(event) => set("firstName")(event.target.value)}
|
||||
/>
|
||||
<Input
|
||||
label="Nom *"
|
||||
required
|
||||
value={form.lastName ?? ""}
|
||||
onChange={(event) => set("lastName")(event.target.value)}
|
||||
/>
|
||||
<Input
|
||||
label="Fonction"
|
||||
value={form.jobTitle ?? ""}
|
||||
onChange={(event) => set("jobTitle")(event.target.value)}
|
||||
/>
|
||||
<Input
|
||||
label="E-mail"
|
||||
type="email"
|
||||
value={form.email ?? ""}
|
||||
onChange={(event) => set("email")(event.target.value)}
|
||||
/>
|
||||
<Input
|
||||
label="Téléphone"
|
||||
value={form.phone ?? ""}
|
||||
onChange={(event) => set("phone")(event.target.value)}
|
||||
/>
|
||||
<Input
|
||||
label="Mobile"
|
||||
value={form.mobile ?? ""}
|
||||
onChange={(event) => set("mobile")(event.target.value)}
|
||||
/>
|
||||
<label className="flex flex-col gap-2 text-sm font-medium text-foreground">
|
||||
Entreprise
|
||||
<select
|
||||
className="h-10 rounded-md border border-border-control bg-background px-3 text-sm"
|
||||
value={form.organizationId ?? ""}
|
||||
onChange={(event) => set("organizationId")(event.target.value || null)}
|
||||
>
|
||||
<option value="">— Aucune —</option>
|
||||
{organizations.map((organization) => (
|
||||
<option key={organization.id} value={organization.id}>
|
||||
{organization.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<label className="flex flex-col gap-2 text-sm font-medium text-foreground">
|
||||
Pays
|
||||
<select
|
||||
className="h-10 rounded-md border border-border-control bg-background px-3 text-sm"
|
||||
value={form.countryId ?? ""}
|
||||
onChange={(event) =>
|
||||
set("countryId")(event.target.value ? Number(event.target.value) : null)
|
||||
}
|
||||
>
|
||||
<option value="">— Aucun —</option>
|
||||
{countries.map((country) => (
|
||||
<option key={country.id} value={country.id}>
|
||||
{country.name} ({country.code})
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<div className="sm:col-span-2">
|
||||
<Input
|
||||
label="Notes"
|
||||
value={form.description ?? ""}
|
||||
onChange={(event) => set("description")(event.target.value)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{error ? (
|
||||
<p className="text-sm text-destructive sm:col-span-2" role="alert">
|
||||
{error}
|
||||
</p>
|
||||
) : null}
|
||||
|
||||
<div className="flex gap-3 sm:col-span-2">
|
||||
<Button type="submit" isLoading={busy}>
|
||||
{editing ? "Enregistrer" : "Créer"}
|
||||
</Button>
|
||||
<Button type="button" variant="secondary" onClick={close}>
|
||||
Annuler
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</CardContent>
|
||||
</Card>
|
||||
) : null}
|
||||
|
||||
{loading ? (
|
||||
<div className="flex flex-col gap-3">
|
||||
<Skeleton className="h-10" />
|
||||
<Skeleton className="h-10" />
|
||||
<Skeleton className="h-10" />
|
||||
</div>
|
||||
) : error && rows.length === 0 ? (
|
||||
<p className="text-sm text-destructive">{error}</p>
|
||||
) : rows.length === 0 ? (
|
||||
<Card>
|
||||
<CardContent>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Aucun prospect. Ajoutez le premier pour commencer.
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
) : (
|
||||
<div className="min-h-0 flex-1 overflow-y-auto overflow-x-auto">
|
||||
<table className="w-full border-collapse text-sm">
|
||||
<thead>
|
||||
<tr className="border-b border-border-control text-left text-xs uppercase tracking-label text-subtle-foreground">
|
||||
<th className="py-2 pr-4">Nom</th>
|
||||
<th className="py-2 pr-4">Fonction</th>
|
||||
<th className="py-2 pr-4">Entreprise</th>
|
||||
<th className="py-2 pr-4">Contact</th>
|
||||
<th className="py-2 pr-4">Pays</th>
|
||||
<th className="py-2 pr-4">Ajouté le</th>
|
||||
<th className="py-2 pr-4 text-right">Actions</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{rows.map((contact) => (
|
||||
<tr key={contact.id} className="border-b border-border-control/60">
|
||||
<td className="py-3 pr-4 font-medium">
|
||||
{contact.last_name} {contact.first_name}
|
||||
</td>
|
||||
<td className="py-3 pr-4">{contact.job_title ?? "—"}</td>
|
||||
<td className="py-3 pr-4">{contact.organization_name ?? "—"}</td>
|
||||
<td className="py-3 pr-4">{contact.email ?? contact.phone ?? "—"}</td>
|
||||
<td className="py-3 pr-4">{contact.country_code ?? "—"}</td>
|
||||
<td className="py-3 pr-4 text-subtle-foreground">
|
||||
{formatDate(contact.created_at)}
|
||||
</td>
|
||||
<td className="py-3 pr-4">
|
||||
<div className="flex justify-end gap-2">
|
||||
<Button size="sm" variant="secondary" onClick={() => openEdit(contact)}>
|
||||
Modifier
|
||||
</Button>
|
||||
{
|
||||
<Button size="sm" variant="destructive" onClick={() => void remove(contact)}>
|
||||
Supprimer
|
||||
</Button>
|
||||
}
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
<p className="mt-3 text-xs text-subtle-foreground">
|
||||
{total} prospect{total > 1 ? "s" : ""}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,226 @@
|
||||
import { useCallback, useEffect, useState, type FormEvent } from "react";
|
||||
import { Button, Card, CardContent, CardHeader, CardTitle, Input, Skeleton } from "@cohaise/ui";
|
||||
import { ApiError, api, type Country } from "../lib/api.js";
|
||||
|
||||
interface Form {
|
||||
code: string;
|
||||
name: string;
|
||||
phoneCode: string;
|
||||
}
|
||||
|
||||
const EMPTY: Form = { code: "", name: "", phoneCode: "" };
|
||||
|
||||
export const Countries = () => {
|
||||
const [rows, setRows] = useState<Country[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [open, setOpen] = useState(false);
|
||||
const [editing, setEditing] = useState<Country | null>(null);
|
||||
const [form, setForm] = useState<Form>(EMPTY);
|
||||
|
||||
const load = useCallback(async () => {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
const result = await api.countries();
|
||||
setRows(result.countries);
|
||||
} catch (caught) {
|
||||
setError(caught instanceof ApiError ? caught.message : "Chargement impossible.");
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
void load();
|
||||
}, [load]);
|
||||
|
||||
const submit = async (event: FormEvent<HTMLFormElement>) => {
|
||||
event.preventDefault();
|
||||
const code = form.code.trim().toUpperCase();
|
||||
const name = form.name.trim();
|
||||
if (!/^[A-Z]{2}$/.test(code)) {
|
||||
setError("Le code doit contenir exactement deux lettres.");
|
||||
return;
|
||||
}
|
||||
if (!name) {
|
||||
setError("Le nom est obligatoire.");
|
||||
return;
|
||||
}
|
||||
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
try {
|
||||
const payload = { code, name, phoneCode: form.phoneCode.trim() || null };
|
||||
if (editing) await api.updateCountry(editing.id, payload);
|
||||
else await api.createCountry(payload);
|
||||
setEditing(null);
|
||||
setForm(EMPTY);
|
||||
setOpen(false);
|
||||
await load();
|
||||
} catch (caught) {
|
||||
setError(caught instanceof ApiError ? caught.message : "Enregistrement impossible.");
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
const remove = async (country: Country) => {
|
||||
if (!window.confirm(`Supprimer « ${country.name} » ?`)) return;
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
try {
|
||||
await api.deleteCountry(country.id);
|
||||
await load();
|
||||
} catch (caught) {
|
||||
setError(caught instanceof ApiError ? caught.message : "Suppression impossible.");
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex min-h-0 flex-1 flex-col gap-6">
|
||||
<div className="flex flex-wrap items-end justify-between gap-4">
|
||||
<p className="max-w-lg text-sm text-muted-foreground">
|
||||
Référentiel ISO 3166 utilisé par les entreprises et les prospects. Il ne contient
|
||||
que les pays déjà saisis dans la base.
|
||||
</p>
|
||||
{
|
||||
<Button
|
||||
onClick={() => {
|
||||
setEditing(null);
|
||||
setForm(EMPTY);
|
||||
setError(null);
|
||||
setOpen(true);
|
||||
}}
|
||||
>
|
||||
Nouveau pays
|
||||
</Button>
|
||||
}
|
||||
</div>
|
||||
|
||||
{open && (
|
||||
<Card className="shrink-0">
|
||||
<CardHeader>
|
||||
<CardTitle>{editing ? "Modifier le pays" : "Nouveau pays"}</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<form
|
||||
className="grid gap-4 sm:grid-cols-3"
|
||||
onSubmit={(event) => void submit(event)}
|
||||
>
|
||||
<Input
|
||||
label="Code *"
|
||||
required
|
||||
maxLength={2}
|
||||
placeholder="FR"
|
||||
value={form.code}
|
||||
onChange={(event) =>
|
||||
setForm((current) => ({ ...current, code: event.target.value.toUpperCase() }))
|
||||
}
|
||||
/>
|
||||
<Input
|
||||
label="Nom *"
|
||||
required
|
||||
value={form.name}
|
||||
onChange={(event) => setForm((current) => ({ ...current, name: event.target.value }))}
|
||||
/>
|
||||
<Input
|
||||
label="Indicatif"
|
||||
placeholder="+33"
|
||||
value={form.phoneCode}
|
||||
onChange={(event) =>
|
||||
setForm((current) => ({ ...current, phoneCode: event.target.value }))
|
||||
}
|
||||
/>
|
||||
|
||||
{error ? (
|
||||
<p className="text-sm text-destructive sm:col-span-3" role="alert">
|
||||
{error}
|
||||
</p>
|
||||
) : null}
|
||||
|
||||
<div className="flex gap-3 sm:col-span-3">
|
||||
<Button type="submit" isLoading={busy}>
|
||||
{editing ? "Enregistrer" : "Créer"}
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant="secondary"
|
||||
onClick={() => {
|
||||
setEditing(null);
|
||||
setForm(EMPTY);
|
||||
setError(null);
|
||||
setOpen(false);
|
||||
}}
|
||||
>
|
||||
Annuler
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{error && rows.length === 0 ? (
|
||||
<p className="text-sm text-destructive">{error}</p>
|
||||
) : loading ? (
|
||||
<div className="flex flex-col gap-3">
|
||||
<Skeleton className="h-10" />
|
||||
<Skeleton className="h-10" />
|
||||
<Skeleton className="h-10" />
|
||||
</div>
|
||||
) : (
|
||||
<div className="min-h-0 flex-1 overflow-y-auto overflow-x-auto">
|
||||
<table className="w-full border-collapse text-sm">
|
||||
<thead>
|
||||
<tr className="border-b border-border-control text-left text-xs uppercase tracking-label text-subtle-foreground">
|
||||
<th className="py-2 pr-4">Code</th>
|
||||
<th className="py-2 pr-4">Nom</th>
|
||||
<th className="py-2 pr-4">Indicatif</th>
|
||||
<th className="py-2 pr-4 text-right">Actions</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{rows.map((country) => (
|
||||
<tr key={country.id} className="border-b border-border-control/60">
|
||||
<td className="py-3 pr-4 font-medium">{country.code}</td>
|
||||
<td className="py-3 pr-4">{country.name}</td>
|
||||
<td className="py-3 pr-4">{country.phone_code ?? "—"}</td>
|
||||
{
|
||||
<td className="py-3 pr-4">
|
||||
<div className="flex justify-end gap-2">
|
||||
<Button
|
||||
size="sm"
|
||||
variant="secondary"
|
||||
onClick={() => {
|
||||
setEditing(country);
|
||||
setForm({
|
||||
code: country.code,
|
||||
name: country.name,
|
||||
phoneCode: country.phone_code ?? "",
|
||||
});
|
||||
setError(null);
|
||||
setOpen(true);
|
||||
}}
|
||||
>
|
||||
Modifier
|
||||
</Button>
|
||||
<Button size="sm" variant="destructive" onClick={() => void remove(country)}>
|
||||
Supprimer
|
||||
</Button>
|
||||
</div>
|
||||
</td>
|
||||
}
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
<p className="mt-3 text-xs text-subtle-foreground">{rows.length} pays</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,85 @@
|
||||
import { useState } from "react";
|
||||
import { Button, cn } from "@cohaise/ui";
|
||||
import type { User } from "../lib/api.js";
|
||||
import { Organizations } from "./Organizations.js";
|
||||
import { Contacts } from "./Contacts.js";
|
||||
import { Countries } from "./Countries.js";
|
||||
import { FaultyTerminalBackdrop } from "../components/FaultyTerminalBackdrop.js";
|
||||
import { ActivityIcon, FolderIcon, LogoutIcon, UsersIcon } from "../components/icons.js";
|
||||
|
||||
type Tab = "organizations" | "contacts" | "countries";
|
||||
|
||||
const TABS: { id: Tab; label: string; icon: typeof FolderIcon }[] = [
|
||||
{ id: "organizations", label: "Entreprises", icon: FolderIcon },
|
||||
{ id: "contacts", label: "Prospects", icon: UsersIcon },
|
||||
{ id: "countries", label: "Pays", icon: ActivityIcon },
|
||||
];
|
||||
|
||||
export const Crm = ({ user, onLogout }: { user: User; onLogout: () => void }) => {
|
||||
const [tab, setTab] = useState<Tab>("organizations");
|
||||
|
||||
return (
|
||||
<div className="relative flex h-dvh flex-col overflow-hidden bg-background text-foreground">
|
||||
<FaultyTerminalBackdrop />
|
||||
|
||||
<div className="relative z-10 flex h-full min-h-0 flex-col gap-3 p-3 sm:p-4">
|
||||
<header className="glass flex shrink-0 items-center justify-between gap-4 rounded-xl border border-border/50 px-4 py-3 shadow-sm">
|
||||
<div className="flex items-center gap-3">
|
||||
<span className="font-logo text-sm font-bold tracking-logo text-accent">COHAISE</span>
|
||||
<span className="text-border" aria-hidden="true">
|
||||
/
|
||||
</span>
|
||||
<span className="font-display text-sm font-semibold uppercase tracking-label">CRM</span>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="hidden text-right sm:block">
|
||||
<p className="text-sm font-medium">
|
||||
{user.first_name} {user.last_name}
|
||||
</p>
|
||||
</div>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={onLogout}
|
||||
iconLeading={<LogoutIcon />}
|
||||
>
|
||||
Se déconnecter
|
||||
</Button>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<nav className="glass flex shrink-0 items-center gap-1 rounded-xl border border-border/50 p-1.5">
|
||||
{TABS.map((item) => {
|
||||
const Icon = item.icon;
|
||||
return (
|
||||
<button
|
||||
key={item.id}
|
||||
type="button"
|
||||
onClick={() => setTab(item.id)}
|
||||
aria-current={tab === item.id ? "page" : undefined}
|
||||
className={cn(
|
||||
"flex items-center gap-2 rounded-lg px-3 py-2 text-sm font-medium transition-colors",
|
||||
tab === item.id
|
||||
? "bg-accent/10 text-accent"
|
||||
: "text-muted-foreground hover:bg-surface-hover hover:text-foreground",
|
||||
)}
|
||||
>
|
||||
<Icon />
|
||||
{item.label}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</nav>
|
||||
|
||||
<main className="glass flex min-h-0 flex-1 flex-col overflow-hidden rounded-xl border border-border/50">
|
||||
<div className="mx-auto flex min-h-0 w-full max-w-6xl flex-1 flex-col px-4 py-6">
|
||||
{tab === "organizations" ? <Organizations /> : null}
|
||||
{tab === "contacts" ? <Contacts /> : null}
|
||||
{tab === "countries" ? <Countries /> : null}
|
||||
</div>
|
||||
</main>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,83 @@
|
||||
import { useState, type FormEvent } from "react";
|
||||
import { Button, Card, CardContent, CardDescription, CardHeader, CardTitle, Input } from "@cohaise/ui";
|
||||
import { ApiError, api, type User } from "../lib/api.js";
|
||||
|
||||
export const Login = ({ onAuthenticated }: { onAuthenticated: (user: User) => void }) => {
|
||||
const [email, setEmail] = useState("");
|
||||
const [password, setPassword] = useState("");
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
const submit = async (event: FormEvent<HTMLFormElement>) => {
|
||||
event.preventDefault();
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
try {
|
||||
const { user } = await api.login(email.trim(), password);
|
||||
onAuthenticated(user);
|
||||
} catch (caught) {
|
||||
setError(caught instanceof ApiError ? caught.message : "Connexion impossible.");
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<main className="flex min-h-dvh items-center justify-center bg-background px-4 py-10">
|
||||
<div className="w-full max-w-sm">
|
||||
<header className="mb-6 text-center">
|
||||
<p className="font-display text-xs font-semibold uppercase tracking-logo text-accent">
|
||||
CoHaiSe
|
||||
</p>
|
||||
<h1 className="font-display mt-2 text-lg font-semibold uppercase tracking-label text-foreground">
|
||||
CRM
|
||||
</h1>
|
||||
<p className="mt-2 text-sm leading-relaxed text-muted-foreground">
|
||||
Connectez-vous pour accéder à vos entreprises et prospects.
|
||||
</p>
|
||||
</header>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Connexion</CardTitle>
|
||||
<CardDescription>Votre session reste ouverte 14 jours.</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<form className="flex flex-col gap-4" onSubmit={(event) => void submit(event)}>
|
||||
<Input
|
||||
label="Adresse e-mail"
|
||||
type="email"
|
||||
name="email"
|
||||
autoComplete="username"
|
||||
required
|
||||
autoFocus
|
||||
placeholder="[email protected]"
|
||||
value={email}
|
||||
onChange={(event) => setEmail(event.target.value)}
|
||||
/>
|
||||
<Input
|
||||
label="Mot de passe"
|
||||
type="password"
|
||||
name="password"
|
||||
autoComplete="current-password"
|
||||
required
|
||||
placeholder="••••••••"
|
||||
value={password}
|
||||
onChange={(event) => setPassword(event.target.value)}
|
||||
{...(error ? { error } : {})}
|
||||
/>
|
||||
|
||||
<Button type="submit" size="lg" fullWidth isLoading={busy}>
|
||||
Se connecter
|
||||
</Button>
|
||||
</form>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<p className="mt-5 text-center text-xs leading-relaxed text-subtle-foreground">
|
||||
Mot de passe oublié ? Contactez un administrateur.
|
||||
</p>
|
||||
</div>
|
||||
</main>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,344 @@
|
||||
import { useCallback, useEffect, useState, type FormEvent } from "react";
|
||||
import { Button, Card, CardContent, CardHeader, CardTitle, Input, Skeleton, Spinner } from "@cohaise/ui";
|
||||
import {
|
||||
ApiError,
|
||||
api,
|
||||
formatDate,
|
||||
type Country,
|
||||
type Organization,
|
||||
type OrganizationInput,
|
||||
} from "../lib/api.js";
|
||||
|
||||
const EMPTY: OrganizationInput = {
|
||||
name: "",
|
||||
website: null,
|
||||
industry: null,
|
||||
phone: null,
|
||||
email: null,
|
||||
addressLine1: null,
|
||||
addressLine2: null,
|
||||
postalCode: null,
|
||||
city: null,
|
||||
countryId: null,
|
||||
description: null,
|
||||
};
|
||||
|
||||
const text = (value: string): string | null => (value.trim() ? value.trim() : null);
|
||||
|
||||
export const Organizations = () => {
|
||||
const [rows, setRows] = useState<Organization[]>([]);
|
||||
const [countries, setCountries] = useState<Country[]>([]);
|
||||
const [total, setTotal] = useState(0);
|
||||
const [search, setSearch] = useState("");
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [editing, setEditing] = useState<Organization | null>(null);
|
||||
const [form, setForm] = useState<OrganizationInput>(EMPTY);
|
||||
// Un etat explicite : comparer form a EMPTY ne fonctionnerait pas, car
|
||||
// saisir puis effacer recrée un objet different de la constante.
|
||||
const [open, setOpen] = useState(false);
|
||||
|
||||
const load = useCallback(async () => {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
const result = await api.organizations(search || undefined);
|
||||
setRows(result.organizations);
|
||||
setTotal(result.total);
|
||||
} catch (caught) {
|
||||
setError(caught instanceof ApiError ? caught.message : "Chargement impossible.");
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [search]);
|
||||
|
||||
useEffect(() => {
|
||||
void load();
|
||||
}, [load]);
|
||||
|
||||
useEffect(() => {
|
||||
void api
|
||||
.countries()
|
||||
.then((result) => setCountries(result.countries))
|
||||
.catch(() => undefined);
|
||||
}, []);
|
||||
|
||||
const openCreate = () => {
|
||||
setEditing(null);
|
||||
setForm(EMPTY);
|
||||
setError(null);
|
||||
setOpen(true);
|
||||
};
|
||||
|
||||
const openEdit = (organization: Organization) => {
|
||||
setOpen(true);
|
||||
setEditing(organization);
|
||||
setForm({
|
||||
name: organization.name,
|
||||
website: organization.website,
|
||||
industry: organization.industry,
|
||||
phone: organization.phone,
|
||||
email: organization.email,
|
||||
addressLine1: organization.address_line1,
|
||||
addressLine2: organization.address_line2,
|
||||
postalCode: organization.postal_code,
|
||||
city: organization.city,
|
||||
countryId: organization.country_id,
|
||||
description: organization.description,
|
||||
});
|
||||
setError(null);
|
||||
};
|
||||
|
||||
const submit = async (event: FormEvent<HTMLFormElement>) => {
|
||||
event.preventDefault();
|
||||
const name = text(form.name ?? "");
|
||||
if (!name) {
|
||||
setError("Le nom de l'entreprise est obligatoire.");
|
||||
return;
|
||||
}
|
||||
|
||||
const payload: OrganizationInput = {
|
||||
name,
|
||||
website: text(form.website ?? ""),
|
||||
industry: text(form.industry ?? ""),
|
||||
phone: text(form.phone ?? ""),
|
||||
email: text(form.email ?? ""),
|
||||
addressLine1: text(form.addressLine1 ?? ""),
|
||||
addressLine2: text(form.addressLine2 ?? ""),
|
||||
postalCode: text(form.postalCode ?? ""),
|
||||
city: text(form.city ?? ""),
|
||||
countryId: form.countryId ?? null,
|
||||
description: text(form.description ?? ""),
|
||||
};
|
||||
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
try {
|
||||
if (editing) await api.updateOrganization(editing.id, payload);
|
||||
else await api.createOrganization(payload);
|
||||
setEditing(null);
|
||||
setForm(EMPTY);
|
||||
setOpen(false);
|
||||
await load();
|
||||
} catch (caught) {
|
||||
setError(caught instanceof ApiError ? caught.message : "Enregistrement impossible.");
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
const remove = async (organization: Organization) => {
|
||||
if (!window.confirm(`Supprimer « ${organization.name} » ? Cette action est réversible par un administrateur.`)) {
|
||||
return;
|
||||
}
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
try {
|
||||
await api.deleteOrganization(organization.id);
|
||||
await load();
|
||||
} catch (caught) {
|
||||
setError(caught instanceof ApiError ? caught.message : "Suppression impossible.");
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
const set = (key: keyof OrganizationInput) => (value: string | number | null) => {
|
||||
setForm((current) => ({
|
||||
...current,
|
||||
[key]: key === "countryId" ? (value === null ? null : Number(value)) : text(String(value ?? "")),
|
||||
}));
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex min-h-0 flex-1 flex-col gap-6">
|
||||
<div className="flex flex-wrap items-end justify-between gap-4">
|
||||
<div className="w-full max-w-xs">
|
||||
<Input
|
||||
label="Rechercher"
|
||||
type="search"
|
||||
placeholder="Nom, ville, secteur…"
|
||||
value={search}
|
||||
onChange={(event) => setSearch(event.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<Button onClick={openCreate}>Nouvelle entreprise</Button>
|
||||
</div>
|
||||
|
||||
{open ? (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>{editing ? "Modifier l'entreprise" : "Nouvelle entreprise"}</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<form className="grid gap-4 sm:grid-cols-2" onSubmit={(event) => void submit(event)}>
|
||||
<Input
|
||||
label="Nom *"
|
||||
required
|
||||
value={form.name ?? ""}
|
||||
onChange={(event) => set("name")(event.target.value)}
|
||||
/>
|
||||
<Input
|
||||
label="Secteur"
|
||||
value={form.industry ?? ""}
|
||||
onChange={(event) => set("industry")(event.target.value)}
|
||||
/>
|
||||
<Input
|
||||
label="Site web"
|
||||
type="url"
|
||||
value={form.website ?? ""}
|
||||
onChange={(event) => set("website")(event.target.value)}
|
||||
/>
|
||||
<Input
|
||||
label="E-mail"
|
||||
type="email"
|
||||
value={form.email ?? ""}
|
||||
onChange={(event) => set("email")(event.target.value)}
|
||||
/>
|
||||
<Input
|
||||
label="Téléphone"
|
||||
value={form.phone ?? ""}
|
||||
onChange={(event) => set("phone")(event.target.value)}
|
||||
/>
|
||||
<label className="flex flex-col gap-2 text-sm font-medium text-foreground">
|
||||
Pays
|
||||
<select
|
||||
className="h-10 rounded-md border border-border-control bg-background px-3 text-sm"
|
||||
value={form.countryId ?? ""}
|
||||
onChange={(event) =>
|
||||
set("countryId")(event.target.value ? Number(event.target.value) : null)
|
||||
}
|
||||
>
|
||||
<option value="">— Aucun —</option>
|
||||
{countries.map((country) => (
|
||||
<option key={country.id} value={country.id}>
|
||||
{country.name} ({country.code})
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<Input
|
||||
label="Adresse"
|
||||
value={form.addressLine1 ?? ""}
|
||||
onChange={(event) => set("addressLine1")(event.target.value)}
|
||||
/>
|
||||
<Input
|
||||
label="Complément"
|
||||
value={form.addressLine2 ?? ""}
|
||||
onChange={(event) => set("addressLine2")(event.target.value)}
|
||||
/>
|
||||
<Input
|
||||
label="Code postal"
|
||||
value={form.postalCode ?? ""}
|
||||
onChange={(event) => set("postalCode")(event.target.value)}
|
||||
/>
|
||||
<Input
|
||||
label="Ville"
|
||||
value={form.city ?? ""}
|
||||
onChange={(event) => set("city")(event.target.value)}
|
||||
/>
|
||||
<div className="sm:col-span-2">
|
||||
<Input
|
||||
label="Notes"
|
||||
value={form.description ?? ""}
|
||||
onChange={(event) => set("description")(event.target.value)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{error ? (
|
||||
<p className="text-sm text-destructive sm:col-span-2" role="alert">
|
||||
{error}
|
||||
</p>
|
||||
) : null}
|
||||
|
||||
<div className="flex gap-3 sm:col-span-2">
|
||||
<Button type="submit" isLoading={busy}>
|
||||
{editing ? "Enregistrer" : "Créer"}
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant="secondary"
|
||||
onClick={() => {
|
||||
setEditing(null);
|
||||
setForm(EMPTY);
|
||||
setError(null);
|
||||
setOpen(false);
|
||||
}}
|
||||
>
|
||||
Annuler
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</CardContent>
|
||||
</Card>
|
||||
) : null}
|
||||
|
||||
{loading ? (
|
||||
<div className="flex flex-col gap-3">
|
||||
<Skeleton className="h-10" />
|
||||
<Skeleton className="h-10" />
|
||||
<Skeleton className="h-10" />
|
||||
</div>
|
||||
) : error && rows.length === 0 ? (
|
||||
<p className="text-sm text-destructive">{error}</p>
|
||||
) : rows.length === 0 ? (
|
||||
<Card>
|
||||
<CardContent>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Aucune entreprise. Créez la première pour commencer.
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
) : (
|
||||
<div className="min-h-0 flex-1 overflow-y-auto overflow-x-auto">
|
||||
<table className="w-full border-collapse text-sm">
|
||||
<thead>
|
||||
<tr className="border-b border-border-control text-left text-xs uppercase tracking-label text-subtle-foreground">
|
||||
<th className="py-2 pr-4">Nom</th>
|
||||
<th className="py-2 pr-4">Ville</th>
|
||||
<th className="py-2 pr-4">Pays</th>
|
||||
<th className="py-2 pr-4">Secteur</th>
|
||||
<th className="py-2 pr-4">Contact</th>
|
||||
<th className="py-2 pr-4">Créée le</th>
|
||||
<th className="py-2 pr-4 text-right">Actions</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{rows.map((organization) => (
|
||||
<tr key={organization.id} className="border-b border-border-control/60">
|
||||
<td className="py-3 pr-4 font-medium">{organization.name}</td>
|
||||
<td className="py-3 pr-4">{organization.city ?? "—"}</td>
|
||||
<td className="py-3 pr-4">{organization.country_code ?? "—"}</td>
|
||||
<td className="py-3 pr-4">{organization.industry ?? "—"}</td>
|
||||
<td className="py-3 pr-4">
|
||||
{organization.email ?? organization.phone ?? "—"}
|
||||
</td>
|
||||
<td className="py-3 pr-4 text-subtle-foreground">
|
||||
{formatDate(organization.created_at)}
|
||||
</td>
|
||||
<td className="py-3 pr-4">
|
||||
<div className="flex justify-end gap-2">
|
||||
<Button size="sm" variant="secondary" onClick={() => openEdit(organization)}>
|
||||
Modifier
|
||||
</Button>
|
||||
{
|
||||
<Button size="sm" variant="destructive" onClick={() => void remove(organization)}>
|
||||
Supprimer
|
||||
</Button>
|
||||
}
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
<p className="mt-3 text-xs text-subtle-foreground">
|
||||
{total} entreprise{total > 1 ? "s" : ""}
|
||||
{loading ? <Spinner size="xs" /> : null}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,4 @@
|
||||
@import "tailwindcss";
|
||||
@import "@cohaise/ui/styles";
|
||||
|
||||
@source "../../../../frontend/shared/src";
|
||||
Reference in New Issue
Block a user