@adatechnology/content-ui 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,2114 @@
1
+ // src/providers/ContentProvider.tsx
2
+ import { createContext, useContext, useMemo } from "react";
3
+
4
+ // src/locales/en.json
5
+ var en_default = {
6
+ statusDraft: "Draft",
7
+ statusScheduled: "Scheduled",
8
+ statusPublished: "Published",
9
+ statusArchived: "Archived",
10
+ listTitle: "Posts",
11
+ newPost: "New post",
12
+ searchLabel: "Search",
13
+ searchPlaceholder: "Title or address",
14
+ filterStatus: "Status",
15
+ filterAll: "All",
16
+ filterTag: "Tag",
17
+ loading: "Loading\u2026",
18
+ empty: "No posts found.",
19
+ loadError: "Could not load.",
20
+ retry: "Try again",
21
+ columnTitle: "Title",
22
+ columnStatus: "Status",
23
+ columnUpdated: "Updated",
24
+ columnPublished: "Publication",
25
+ paginationLabel: "Pagination",
26
+ paginationPrevious: "Previous",
27
+ paginationNext: "Next",
28
+ pageLabel: "Page {page}",
29
+ editorNewTitle: "New post",
30
+ editorEditTitle: "Edit post",
31
+ fieldTitle: "Title",
32
+ fieldSlug: "Address (slug)",
33
+ fieldSlugHint: "Shown in the URL. Changing it after publishing breaks links already shared.",
34
+ fieldExcerpt: "Excerpt",
35
+ fieldBody: "Content",
36
+ bodyHint: "Markdown: # heading, **bold**, *italic*, - list, [link](https://\u2026), ![image](https://\u2026)",
37
+ tabWrite: "Write",
38
+ tabPreview: "Preview",
39
+ previewEmpty: "Nothing to preview.",
40
+ fieldCover: "Cover image",
41
+ fieldCoverUrl: "Image URL",
42
+ fieldCoverAlt: "Image description (alt text)",
43
+ coverUpload: "Upload image",
44
+ coverRemove: "Remove cover",
45
+ coverTooLarge: "The image is larger than 1 MB.",
46
+ coverInvalidType: "Use JPG, PNG or WebP.",
47
+ coverUploading: "Uploading\u2026",
48
+ coverUploadError: "Could not upload the image.",
49
+ fieldTags: "Tags",
50
+ tagsHint: "Enter or comma to add",
51
+ tagRemove: "Remove tag {tag}",
52
+ fieldAuthor: "Author",
53
+ seoSection: "SEO",
54
+ fieldSeoTitle: "Search engine title",
55
+ fieldSeoDescription: "Search engine description",
56
+ fieldCanonical: "Canonical URL",
57
+ publishSection: "Publishing",
58
+ scheduleAt: "Schedule for",
59
+ save: "Save draft",
60
+ saveChanges: "Save",
61
+ saving: "Saving\u2026",
62
+ saved: "Saved.",
63
+ publishNow: "Publish now",
64
+ schedule: "Schedule",
65
+ unpublish: "Unpublish",
66
+ archive: "Archive",
67
+ archiveConfirm: "Archive this post? It will leave the site.",
68
+ close: "Back",
69
+ unsavedConfirm: "You have unsaved changes. Leave anyway?",
70
+ unsavedBadge: "Unsaved changes",
71
+ saveError: "Could not save.",
72
+ errorTitle: "Enter a title.",
73
+ errorSlug: "Use lowercase letters, numbers and hyphens.",
74
+ errorUrl: "Use a full http(s) address.",
75
+ errorSchedule: "Pick a date and time.",
76
+ scheduledFor: "Scheduled for {date}",
77
+ publishedOn: "Published on {date}",
78
+ readingTime: "{minutes} min read",
79
+ readMore: "Read more",
80
+ byAuthor: "By {author}",
81
+ allTags: "All",
82
+ tagsLabel: "Filter by tag",
83
+ shareLabel: "Share",
84
+ shareWhatsApp: "WhatsApp",
85
+ shareFacebook: "Facebook",
86
+ shareX: "X",
87
+ shareLinkedIn: "LinkedIn",
88
+ copyLink: "Copy link",
89
+ linkCopied: "Link copied",
90
+ shareNative: "Share\u2026",
91
+ shareOn: "Share on {network}",
92
+ notFound: "Post not found.",
93
+ postsEmpty: "No posts published yet.",
94
+ clearFilters: "Clear filters",
95
+ bodyHintToolbar: "Select text and use the buttons above. Shortcuts: Ctrl+B bold, Ctrl+I italic, Ctrl+K link.",
96
+ toolbarLabel: "Text formatting",
97
+ formatBold: "Bold",
98
+ formatItalic: "Italic",
99
+ formatHeading2: "Heading",
100
+ formatHeading3: "Subheading",
101
+ formatBulletList: "Bulleted list",
102
+ formatNumberedList: "Numbered list",
103
+ formatQuote: "Quote",
104
+ formatLink: "Link",
105
+ formatImage: "Image",
106
+ formatEmoji: "Emoji",
107
+ formatSampleText: "text",
108
+ linkDialogTitle: "Insert link",
109
+ linkUrl: "Link address (URL)",
110
+ linkText: "Link text",
111
+ imageDialogTitle: "Insert image",
112
+ imageUploadFromDevice: "Upload from device",
113
+ dialogInsert: "Insert",
114
+ dialogCancel: "Cancel",
115
+ fileNoneChosen: "No file chosen",
116
+ emojiTitle: "Choose emoji",
117
+ emojiSearch: "Search emoji",
118
+ emojiCategories: "Emoji categories",
119
+ emojiEmpty: "No emoji found.",
120
+ emojiSmileys: "Faces",
121
+ emojiGestures: "Gestures",
122
+ emojiFood: "Food",
123
+ emojiNature: "Nature",
124
+ emojiTravel: "Places",
125
+ emojiObjects: "Objects",
126
+ emojiSymbols: "Symbols"
127
+ };
128
+
129
+ // src/locales/pt-BR.json
130
+ var pt_BR_default = {
131
+ statusDraft: "Rascunho",
132
+ statusScheduled: "Agendado",
133
+ statusPublished: "Publicado",
134
+ statusArchived: "Arquivado",
135
+ listTitle: "Posts",
136
+ newPost: "Novo post",
137
+ searchLabel: "Buscar",
138
+ searchPlaceholder: "T\xEDtulo ou endere\xE7o",
139
+ filterStatus: "Status",
140
+ filterAll: "Todos",
141
+ filterTag: "Tag",
142
+ loading: "Carregando\u2026",
143
+ empty: "Nenhum post encontrado.",
144
+ loadError: "N\xE3o foi poss\xEDvel carregar.",
145
+ retry: "Tentar de novo",
146
+ columnTitle: "T\xEDtulo",
147
+ columnStatus: "Status",
148
+ columnUpdated: "Atualizado",
149
+ columnPublished: "Publica\xE7\xE3o",
150
+ paginationLabel: "Pagina\xE7\xE3o",
151
+ paginationPrevious: "Anterior",
152
+ paginationNext: "Pr\xF3xima",
153
+ pageLabel: "P\xE1gina {page}",
154
+ editorNewTitle: "Novo post",
155
+ editorEditTitle: "Editar post",
156
+ fieldTitle: "T\xEDtulo",
157
+ fieldSlug: "Endere\xE7o (slug)",
158
+ fieldSlugHint: "Aparece na URL. Mudar depois de publicado quebra links j\xE1 compartilhados.",
159
+ fieldExcerpt: "Resumo",
160
+ fieldBody: "Conte\xFAdo",
161
+ bodyHint: "Markdown: # t\xEDtulo, **negrito**, *it\xE1lico*, - lista, [link](https://\u2026), ![imagem](https://\u2026)",
162
+ tabWrite: "Escrever",
163
+ tabPreview: "Pr\xE9-visualizar",
164
+ previewEmpty: "Nada para pr\xE9-visualizar.",
165
+ fieldCover: "Imagem de capa",
166
+ fieldCoverUrl: "URL da imagem",
167
+ fieldCoverAlt: "Descri\xE7\xE3o da imagem (texto alternativo)",
168
+ coverUpload: "Enviar imagem",
169
+ coverRemove: "Remover capa",
170
+ coverTooLarge: "A imagem passa de 1 MB.",
171
+ coverInvalidType: "Use JPG, PNG ou WebP.",
172
+ coverUploading: "Enviando\u2026",
173
+ coverUploadError: "N\xE3o foi poss\xEDvel enviar a imagem.",
174
+ fieldTags: "Tags",
175
+ tagsHint: "Enter ou v\xEDrgula para adicionar",
176
+ tagRemove: "Remover tag {tag}",
177
+ fieldAuthor: "Autor",
178
+ seoSection: "SEO",
179
+ fieldSeoTitle: "T\xEDtulo para buscadores",
180
+ fieldSeoDescription: "Descri\xE7\xE3o para buscadores",
181
+ fieldCanonical: "URL can\xF4nica",
182
+ publishSection: "Publica\xE7\xE3o",
183
+ scheduleAt: "Agendar para",
184
+ save: "Salvar rascunho",
185
+ saveChanges: "Salvar",
186
+ saving: "Salvando\u2026",
187
+ saved: "Salvo.",
188
+ publishNow: "Publicar agora",
189
+ schedule: "Agendar",
190
+ unpublish: "Despublicar",
191
+ archive: "Arquivar",
192
+ archiveConfirm: "Arquivar este post? Ele sai do site.",
193
+ close: "Voltar",
194
+ unsavedConfirm: "H\xE1 altera\xE7\xF5es n\xE3o salvas. Sair mesmo assim?",
195
+ unsavedBadge: "Altera\xE7\xF5es n\xE3o salvas",
196
+ saveError: "N\xE3o foi poss\xEDvel salvar.",
197
+ errorTitle: "Informe o t\xEDtulo.",
198
+ errorSlug: "Use letras min\xFAsculas, n\xFAmeros e h\xEDfen.",
199
+ errorUrl: "Use um endere\xE7o http(s) completo.",
200
+ errorSchedule: "Escolha uma data e hora.",
201
+ scheduledFor: "Agendado para {date}",
202
+ publishedOn: "Publicado em {date}",
203
+ readingTime: "{minutes} min de leitura",
204
+ readMore: "Ler mais",
205
+ byAuthor: "Por {author}",
206
+ allTags: "Todos",
207
+ tagsLabel: "Filtrar por tag",
208
+ shareLabel: "Compartilhar",
209
+ shareWhatsApp: "WhatsApp",
210
+ shareFacebook: "Facebook",
211
+ shareX: "X",
212
+ shareLinkedIn: "LinkedIn",
213
+ copyLink: "Copiar link",
214
+ linkCopied: "Link copiado",
215
+ shareNative: "Compartilhar\u2026",
216
+ shareOn: "Compartilhar no {network}",
217
+ notFound: "Post n\xE3o encontrado.",
218
+ postsEmpty: "Nenhum post publicado ainda.",
219
+ clearFilters: "Limpar filtros",
220
+ bodyHintToolbar: "Selecione o texto e use os bot\xF5es acima. Atalhos: Ctrl+B negrito, Ctrl+I it\xE1lico, Ctrl+K link.",
221
+ toolbarLabel: "Formata\xE7\xE3o do texto",
222
+ formatBold: "Negrito",
223
+ formatItalic: "It\xE1lico",
224
+ formatHeading2: "T\xEDtulo",
225
+ formatHeading3: "Subt\xEDtulo",
226
+ formatBulletList: "Lista com marcadores",
227
+ formatNumberedList: "Lista numerada",
228
+ formatQuote: "Cita\xE7\xE3o",
229
+ formatLink: "Link",
230
+ formatImage: "Imagem",
231
+ formatEmoji: "Emoji",
232
+ formatSampleText: "texto",
233
+ linkDialogTitle: "Inserir link",
234
+ linkUrl: "Endere\xE7o do link (URL)",
235
+ linkText: "Texto do link",
236
+ imageDialogTitle: "Inserir imagem",
237
+ imageUploadFromDevice: "Enviar do aparelho",
238
+ dialogInsert: "Inserir",
239
+ dialogCancel: "Cancelar",
240
+ fileNoneChosen: "Nenhum arquivo escolhido",
241
+ emojiTitle: "Escolher emoji",
242
+ emojiSearch: "Buscar emoji",
243
+ emojiCategories: "Categorias de emoji",
244
+ emojiEmpty: "Nenhum emoji encontrado.",
245
+ emojiSmileys: "Rostos",
246
+ emojiGestures: "Gestos",
247
+ emojiFood: "Comida",
248
+ emojiNature: "Natureza",
249
+ emojiTravel: "Lugares",
250
+ emojiObjects: "Objetos",
251
+ emojiSymbols: "S\xEDmbolos"
252
+ };
253
+
254
+ // src/locales/index.ts
255
+ var DEFAULT_CONTENT_LOCALE = "pt-BR";
256
+ var MESSAGES_BY_LOCALE = { "pt-BR": pt_BR_default, en: en_default };
257
+ function resolveContentMessages(locale) {
258
+ return MESSAGES_BY_LOCALE[locale] ?? MESSAGES_BY_LOCALE[DEFAULT_CONTENT_LOCALE];
259
+ }
260
+ function interpolate(message, values) {
261
+ return message.replace(/\{(\w+)\}/g, (match, key) => key in values ? String(values[key]) : match);
262
+ }
263
+
264
+ // src/providers/ContentProvider.tsx
265
+ import { jsx } from "react/jsx-runtime";
266
+ var ContentContext = createContext(null);
267
+ function defaultRenderLink({ children, ...props }) {
268
+ return /* @__PURE__ */ jsx("a", { ...props, children });
269
+ }
270
+ function ContentProvider({
271
+ adminApi,
272
+ publicApi,
273
+ locale = DEFAULT_CONTENT_LOCALE,
274
+ messages,
275
+ renderLink,
276
+ children
277
+ }) {
278
+ const value = useMemo(
279
+ () => ({
280
+ ...adminApi ? { adminApi } : {},
281
+ ...publicApi ? { publicApi } : {},
282
+ locale,
283
+ messages: { ...resolveContentMessages(locale), ...messages },
284
+ renderLink: renderLink ?? defaultRenderLink
285
+ }),
286
+ [adminApi, publicApi, locale, messages, renderLink]
287
+ );
288
+ return /* @__PURE__ */ jsx(ContentContext.Provider, { value, children });
289
+ }
290
+ function useContentContext() {
291
+ const value = useContext(ContentContext);
292
+ if (!value) throw new Error("content-ui: componente usado fora de <ContentProvider>");
293
+ return value;
294
+ }
295
+ function useContentAdminApi() {
296
+ const { adminApi } = useContentContext();
297
+ if (!adminApi) throw new Error("content-ui: <ContentProvider adminApi> \xE9 obrigat\xF3rio no painel");
298
+ return adminApi;
299
+ }
300
+ function useContentPublicApi() {
301
+ const { publicApi } = useContentContext();
302
+ if (!publicApi) throw new Error("content-ui: <ContentProvider publicApi> \xE9 obrigat\xF3rio no site p\xFAblico");
303
+ return publicApi;
304
+ }
305
+ function useContentText() {
306
+ const { messages, locale } = useContentContext();
307
+ return useMemo(
308
+ () => ({ messages, locale, format: (key, values) => interpolate(messages[key], values) }),
309
+ [messages, locale]
310
+ );
311
+ }
312
+ function useRenderLink() {
313
+ return useContentContext().renderLink;
314
+ }
315
+
316
+ // src/components/ContentWorkspace.tsx
317
+ import { useState as useState11 } from "react";
318
+
319
+ // src/components/PostEditor.tsx
320
+ import { Archive as Archive2, ArrowLeft, CalendarClock as CalendarClock2, EyeOff, Save, Send, Trash2 } from "lucide-react";
321
+ import { useId as useId5, useState as useState9 } from "react";
322
+
323
+ // src/hooks/usePostEditor.ts
324
+ import { useCallback as useCallback2, useEffect as useEffect2, useMemo as useMemo2, useState as useState2 } from "react";
325
+
326
+ // src/lib/format.ts
327
+ function formatPostDate(iso, locale, withTime = false) {
328
+ if (!iso) return "";
329
+ const date = new Date(iso);
330
+ if (Number.isNaN(date.getTime())) return "";
331
+ return new Intl.DateTimeFormat(locale, {
332
+ dateStyle: "long",
333
+ ...withTime ? { timeStyle: "short" } : {}
334
+ }).format(date);
335
+ }
336
+ function pad(value) {
337
+ return String(value).padStart(2, "0");
338
+ }
339
+ function toDateTimeLocalValue(iso) {
340
+ if (!iso) return "";
341
+ const date = new Date(iso);
342
+ if (Number.isNaN(date.getTime())) return "";
343
+ return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}T${pad(date.getHours())}:${pad(date.getMinutes())}`;
344
+ }
345
+ function fromDateTimeLocalValue(value) {
346
+ if (!value) return void 0;
347
+ const date = new Date(value);
348
+ return Number.isNaN(date.getTime()) ? void 0 : date.toISOString();
349
+ }
350
+
351
+ // src/lib/postDraft.ts
352
+ import { createPostSchema, slugify } from "@adatechnology/content-contracts";
353
+ var EMPTY_POST_DRAFT = {
354
+ title: "",
355
+ slug: "",
356
+ excerpt: "",
357
+ body: "",
358
+ coverImageUrl: "",
359
+ coverImageAlt: "",
360
+ tags: [],
361
+ authorName: "",
362
+ seoTitle: "",
363
+ seoDescription: "",
364
+ canonicalUrl: ""
365
+ };
366
+ function draftFromPost(post, defaults = {}) {
367
+ if (!post) return { ...EMPTY_POST_DRAFT, ...defaults };
368
+ return {
369
+ title: post.title,
370
+ slug: post.slug,
371
+ excerpt: post.excerpt ?? "",
372
+ body: post.body,
373
+ coverImageUrl: post.coverImageUrl ?? "",
374
+ coverImageAlt: post.coverImageAlt ?? "",
375
+ tags: post.tags,
376
+ authorName: post.authorName ?? "",
377
+ seoTitle: post.seoTitle ?? "",
378
+ seoDescription: post.seoDescription ?? "",
379
+ canonicalUrl: post.canonicalUrl ?? ""
380
+ };
381
+ }
382
+ var nullable = (value) => value.trim() ? value.trim() : null;
383
+ function draftToInput(draft) {
384
+ return {
385
+ title: draft.title.trim(),
386
+ ...draft.slug.trim() ? { slug: draft.slug.trim() } : {},
387
+ excerpt: nullable(draft.excerpt),
388
+ body: draft.body,
389
+ coverImageUrl: nullable(draft.coverImageUrl),
390
+ coverImageAlt: nullable(draft.coverImageAlt),
391
+ tags: [...draft.tags],
392
+ authorName: nullable(draft.authorName),
393
+ seoTitle: nullable(draft.seoTitle),
394
+ seoDescription: nullable(draft.seoDescription),
395
+ canonicalUrl: nullable(draft.canonicalUrl)
396
+ };
397
+ }
398
+ function isDraftDirty(draft, baseline) {
399
+ return JSON.stringify(draft) !== JSON.stringify(baseline);
400
+ }
401
+ function deriveSlug(params) {
402
+ return params.slugTouched ? params.slug : slugify(params.title);
403
+ }
404
+ var DRAFT_ERROR = {
405
+ TITLE: "title",
406
+ SLUG: "slug",
407
+ COVER_IMAGE_URL: "coverImageUrl",
408
+ CANONICAL_URL: "canonicalUrl"
409
+ };
410
+ function validateDraft(draft) {
411
+ const result = createPostSchema.safeParse(draftToInput(draft));
412
+ if (result.success) return {};
413
+ const errors = {};
414
+ for (const issue of result.error.issues) {
415
+ const field = issue.path[0];
416
+ if (field === "title" || field === "slug" || field === "coverImageUrl" || field === "canonicalUrl")
417
+ errors[field] = true;
418
+ }
419
+ return errors;
420
+ }
421
+ function splitTagInput(value) {
422
+ return value.split(/[,\n]/).map((tag) => tag.trim().replace(/\s+/g, " ").toLowerCase()).filter(Boolean);
423
+ }
424
+
425
+ // src/hooks/useAsyncResource.ts
426
+ import { useCallback, useEffect, useRef, useState } from "react";
427
+ function useAsyncResource(load, key) {
428
+ const [state, setState] = useState({ isLoading: true });
429
+ const [attempt, setAttempt] = useState(0);
430
+ const loadRef = useRef(load);
431
+ loadRef.current = load;
432
+ useEffect(() => {
433
+ let isCurrent = true;
434
+ setState((previous) => ({ ...previous, isLoading: true, error: void 0 }));
435
+ loadRef.current().then((data) => {
436
+ if (isCurrent) setState({ data, isLoading: false });
437
+ }).catch((error) => {
438
+ if (isCurrent) setState({ isLoading: false, error });
439
+ });
440
+ return () => {
441
+ isCurrent = false;
442
+ };
443
+ }, [key, attempt]);
444
+ const reload = useCallback(() => setAttempt((value) => value + 1), []);
445
+ return { data: state.data, isLoading: state.isLoading, error: state.error, reload };
446
+ }
447
+
448
+ // src/hooks/usePostEditor.ts
449
+ var COVER_MAX_BYTES = 1024 * 1024;
450
+ var COVER_MIME_TYPES = ["image/jpeg", "image/png", "image/webp"];
451
+ function usePostEditor(params) {
452
+ const api = useContentAdminApi();
453
+ const [post, setPost] = useState2();
454
+ const [isLoading, setIsLoading] = useState2(Boolean(params.postId));
455
+ const [baseline, setBaseline] = useState2(() => draftFromPost(void 0, params.defaults));
456
+ const [draft, setDraft] = useState2(baseline);
457
+ const [slugTouched, setSlugTouched] = useState2(Boolean(params.postId));
458
+ const [scheduleAt, setScheduleAt] = useState2("");
459
+ const [isBusy, setIsBusy] = useState2(false);
460
+ const [isUploading, setIsUploading] = useState2(false);
461
+ const [feedback, setFeedback] = useState2();
462
+ const [showErrors, setShowErrors] = useState2(false);
463
+ const tags = useAsyncResource(
464
+ () => api.listTags ? api.listTags() : Promise.resolve([]),
465
+ "editor-tags"
466
+ );
467
+ const accept = useCallback2((saved) => {
468
+ const next = draftFromPost(saved);
469
+ setPost(saved);
470
+ setBaseline(next);
471
+ setDraft(next);
472
+ setSlugTouched(true);
473
+ setScheduleAt(saved.status === "scheduled" ? toDateTimeLocalValue(saved.publishedAt) : "");
474
+ }, []);
475
+ useEffect2(() => {
476
+ if (!params.postId) return void 0;
477
+ let isCurrent = true;
478
+ setIsLoading(true);
479
+ api.getPost(params.postId).then((loaded) => {
480
+ if (!isCurrent) return;
481
+ accept(loaded);
482
+ setIsLoading(false);
483
+ }).catch(() => {
484
+ if (isCurrent) setIsLoading(false);
485
+ });
486
+ return () => {
487
+ isCurrent = false;
488
+ };
489
+ }, [params.postId, api, accept]);
490
+ const errors = useMemo2(() => validateDraft(draft), [draft]);
491
+ const isDirty = isDraftDirty(draft, baseline);
492
+ const isValid = Object.keys(errors).length === 0;
493
+ function update(field, value) {
494
+ setFeedback(void 0);
495
+ setDraft((current) => {
496
+ const next = { ...current, [field]: value };
497
+ if (field === "title" && !post)
498
+ return { ...next, slug: deriveSlug({ title: next.title, slug: next.slug, slugTouched }) };
499
+ return next;
500
+ });
501
+ if (field === "slug") setSlugTouched(true);
502
+ }
503
+ async function run(action) {
504
+ setShowErrors(true);
505
+ if (!isValid) return void 0;
506
+ setIsBusy(true);
507
+ try {
508
+ const saved = await action();
509
+ accept(saved);
510
+ setFeedback("saved");
511
+ params.onSaved?.(saved);
512
+ return saved;
513
+ } catch {
514
+ setFeedback("saveError");
515
+ return void 0;
516
+ } finally {
517
+ setIsBusy(false);
518
+ }
519
+ }
520
+ async function persist() {
521
+ const input = draftToInput(draft);
522
+ if (!post) return api.createPost(input);
523
+ if (!isDirty) return post;
524
+ return api.updatePost(post.id, input);
525
+ }
526
+ const save = () => run(persist);
527
+ const publishNow = () => run(async () => api.publishPost((await persist()).id));
528
+ const schedule = () => {
529
+ const publishedAt = fromDateTimeLocalValue(scheduleAt);
530
+ if (!publishedAt) {
531
+ setFeedback("errorSchedule");
532
+ return Promise.resolve(void 0);
533
+ }
534
+ return run(async () => api.publishPost((await persist()).id, { publishedAt }));
535
+ };
536
+ const unpublish = () => run(async () => api.unpublishPost((await persist()).id));
537
+ async function archive() {
538
+ if (!post) return;
539
+ setIsBusy(true);
540
+ try {
541
+ await api.archivePost(post.id);
542
+ const archived = { ...post, status: "archived" };
543
+ setPost(archived);
544
+ params.onArchived?.(archived);
545
+ } catch {
546
+ setFeedback("saveError");
547
+ } finally {
548
+ setIsBusy(false);
549
+ }
550
+ }
551
+ async function uploadImage(file) {
552
+ if (!api.uploadCoverImage) return { error: "coverUploadError" };
553
+ if (!COVER_MIME_TYPES.includes(file.type)) return { error: "coverInvalidType" };
554
+ if (file.size > COVER_MAX_BYTES) return { error: "coverTooLarge" };
555
+ setIsUploading(true);
556
+ try {
557
+ const { url } = await api.uploadCoverImage(file);
558
+ return { url };
559
+ } catch {
560
+ return { error: "coverUploadError" };
561
+ } finally {
562
+ setIsUploading(false);
563
+ }
564
+ }
565
+ async function uploadCover(file) {
566
+ const result = await uploadImage(file);
567
+ if ("error" in result) return setFeedback(result.error);
568
+ update("coverImageUrl", result.url);
569
+ }
570
+ return {
571
+ post,
572
+ draft,
573
+ update,
574
+ errors: showErrors ? errors : {},
575
+ isLoading,
576
+ isDirty,
577
+ isBusy,
578
+ isUploading,
579
+ feedback,
580
+ scheduleAt,
581
+ setScheduleAt,
582
+ canUploadCover: Boolean(api.uploadCoverImage),
583
+ tagSuggestions: (tags.data ?? []).map((entry) => entry.tag),
584
+ save,
585
+ publishNow,
586
+ schedule,
587
+ unpublish,
588
+ archive,
589
+ uploadCover,
590
+ uploadImage
591
+ };
592
+ }
593
+
594
+ // src/hooks/useUnsavedChangesGuard.ts
595
+ import { useCallback as useCallback3, useEffect as useEffect3 } from "react";
596
+ function useUnsavedChangesGuard(isDirty, message) {
597
+ useEffect3(() => {
598
+ if (!isDirty) return void 0;
599
+ const handleBeforeUnload = (event) => {
600
+ event.preventDefault();
601
+ event.returnValue = "";
602
+ };
603
+ window.addEventListener("beforeunload", handleBeforeUnload);
604
+ return () => window.removeEventListener("beforeunload", handleBeforeUnload);
605
+ }, [isDirty]);
606
+ const confirmLeave = useCallback3(() => !isDirty || window.confirm(message), [isDirty, message]);
607
+ return { confirmLeave };
608
+ }
609
+
610
+ // src/components/FilePicker.tsx
611
+ import { ImageUp } from "lucide-react";
612
+ import { useRef as useRef2, useState as useState3 } from "react";
613
+ import { jsx as jsx2, jsxs } from "react/jsx-runtime";
614
+ function FilePicker({ buttonLabel, emptyLabel, accept, isBusy = false, onPick }) {
615
+ const inputRef = useRef2(null);
616
+ const [fileName, setFileName] = useState3("");
617
+ return /* @__PURE__ */ jsxs("div", { className: "adc-file-picker", children: [
618
+ /* @__PURE__ */ jsxs("button", { type: "button", className: "adc-button", disabled: isBusy, onClick: () => inputRef.current?.click(), children: [
619
+ /* @__PURE__ */ jsx2(ImageUp, { "aria-hidden": "true", className: "adc-icon" }),
620
+ buttonLabel
621
+ ] }),
622
+ /* @__PURE__ */ jsx2("span", { className: "adc-file-name", "aria-live": "polite", children: fileName || emptyLabel }),
623
+ /* @__PURE__ */ jsx2(
624
+ "input",
625
+ {
626
+ ref: inputRef,
627
+ hidden: true,
628
+ type: "file",
629
+ accept,
630
+ onChange: (event) => {
631
+ const file = event.target.files?.[0];
632
+ event.target.value = "";
633
+ if (!file) return;
634
+ setFileName(file.name);
635
+ onPick(file);
636
+ }
637
+ }
638
+ )
639
+ ] });
640
+ }
641
+
642
+ // src/components/MarkdownContent.tsx
643
+ import {
644
+ createHeadingIdGenerator,
645
+ DEFAULT_LINK_REL,
646
+ inlineToPlainText,
647
+ isAbsoluteHttpUrl,
648
+ parseMarkdown,
649
+ resolveHeadingLevel
650
+ } from "@adatechnology/content-contracts";
651
+ import { useMemo as useMemo3 } from "react";
652
+ import { jsx as jsx3 } from "react/jsx-runtime";
653
+ function renderInline(nodes) {
654
+ return nodes.map((node, index) => {
655
+ switch (node.type) {
656
+ case "text":
657
+ return node.value;
658
+ case "strong":
659
+ return /* @__PURE__ */ jsx3("strong", { children: renderInline(node.children) }, index);
660
+ case "emphasis":
661
+ return /* @__PURE__ */ jsx3("em", { children: renderInline(node.children) }, index);
662
+ case "strikethrough":
663
+ return /* @__PURE__ */ jsx3("del", { children: renderInline(node.children) }, index);
664
+ case "inlineCode":
665
+ return /* @__PURE__ */ jsx3("code", { children: node.value }, index);
666
+ case "break":
667
+ return /* @__PURE__ */ jsx3("br", {}, index);
668
+ case "image":
669
+ return /* @__PURE__ */ jsx3("img", { src: node.src, alt: node.alt, title: node.title, loading: "lazy", decoding: "async" }, index);
670
+ case "link":
671
+ return /* @__PURE__ */ jsx3(
672
+ "a",
673
+ {
674
+ href: node.href,
675
+ title: node.title,
676
+ rel: DEFAULT_LINK_REL,
677
+ ...isAbsoluteHttpUrl(node.href) ? { target: "_blank" } : {},
678
+ children: renderInline(node.children)
679
+ },
680
+ index
681
+ );
682
+ }
683
+ });
684
+ }
685
+ function renderBlock(block, key, context, tight = false) {
686
+ switch (block.type) {
687
+ case "heading": {
688
+ const Tag = `h${resolveHeadingLevel(block.level, context.offset)}`;
689
+ return /* @__PURE__ */ jsx3(Tag, { id: context.nextHeadingId(inlineToPlainText(block.children)), children: renderInline(block.children) }, key);
690
+ }
691
+ case "paragraph":
692
+ return tight ? /* @__PURE__ */ jsx3("span", { children: renderInline(block.children) }, key) : /* @__PURE__ */ jsx3("p", { children: renderInline(block.children) }, key);
693
+ case "blockquote":
694
+ return /* @__PURE__ */ jsx3("blockquote", { children: block.children.map((child, index) => renderBlock(child, index, context)) }, key);
695
+ case "codeBlock":
696
+ return /* @__PURE__ */ jsx3("pre", { children: /* @__PURE__ */ jsx3("code", { className: block.language ? `language-${block.language}` : void 0, children: block.value }) }, key);
697
+ case "thematicBreak":
698
+ return /* @__PURE__ */ jsx3("hr", {}, key);
699
+ case "list": {
700
+ const items = block.items.map((item, index) => /* @__PURE__ */ jsx3("li", { children: item.map((child, childIndex) => renderBlock(child, childIndex, context, block.tight)) }, index));
701
+ return block.ordered ? /* @__PURE__ */ jsx3("ol", { start: block.start, children: items }, key) : /* @__PURE__ */ jsx3("ul", { children: items }, key);
702
+ }
703
+ }
704
+ }
705
+ function MarkdownContent({ markdown, headingLevelOffset = 0, className }) {
706
+ const document = useMemo3(() => parseMarkdown(markdown), [markdown]);
707
+ const context = { offset: headingLevelOffset, nextHeadingId: createHeadingIdGenerator() };
708
+ return /* @__PURE__ */ jsx3("div", { className: ["adc-prose", className].filter(Boolean).join(" "), children: document.children.map((block, index) => renderBlock(block, index, context)) });
709
+ }
710
+
711
+ // src/components/MarkdownEditor.tsx
712
+ import {
713
+ Bold,
714
+ Heading2,
715
+ Heading3,
716
+ Image as ImageIcon,
717
+ Italic,
718
+ Link as LinkIcon,
719
+ List,
720
+ ListOrdered,
721
+ Quote,
722
+ Smile
723
+ } from "lucide-react";
724
+ import { useLayoutEffect, useRef as useRef3, useState as useState7 } from "react";
725
+
726
+ // src/lib/markdownFormat.ts
727
+ var LINE_PREFIX_PATTERN = {
728
+ heading2: /^## /,
729
+ heading3: /^### /,
730
+ bulletList: /^[-*+] /,
731
+ numberedList: /^\d+\. /,
732
+ quote: /^> /
733
+ };
734
+ var ANY_BLOCK_PREFIX = /^(#{1,6} |[-*+] |\d+\. |> )/;
735
+ function replaceRange(source, from, to, text, select) {
736
+ return {
737
+ value: source.value.slice(0, from) + text + source.value.slice(to),
738
+ start: from + select[0],
739
+ end: from + select[1]
740
+ };
741
+ }
742
+ function insertText(source, text) {
743
+ return replaceRange(source, source.start, source.end, text, [text.length, text.length]);
744
+ }
745
+ function toggleWrap(source, marker, placeholder) {
746
+ const { value, start, end } = source;
747
+ const selected = value.slice(start, end);
748
+ const isWrappedOutside = value.slice(start - marker.length, start) === marker && value.slice(end, end + marker.length) === marker;
749
+ if (isWrappedOutside && start >= marker.length) {
750
+ return replaceRange(source, start - marker.length, end + marker.length, selected, [0, selected.length]);
751
+ }
752
+ const isWrappedInside = selected.length > marker.length * 2 && selected.startsWith(marker) && selected.endsWith(marker);
753
+ if (isWrappedInside) {
754
+ const inner = selected.slice(marker.length, selected.length - marker.length);
755
+ return replaceRange(source, start, end, inner, [0, inner.length]);
756
+ }
757
+ const content = selected || placeholder;
758
+ return replaceRange(source, start, end, `${marker}${content}${marker}`, [
759
+ marker.length,
760
+ marker.length + content.length
761
+ ]);
762
+ }
763
+ function lineBounds(value, start, end) {
764
+ const from = value.lastIndexOf("\n", start - 1) + 1;
765
+ const nextBreak = value.indexOf("\n", end > start && value[end - 1] === "\n" ? end - 1 : end);
766
+ return { from, to: nextBreak === -1 ? value.length : nextBreak };
767
+ }
768
+ function toggleLinePrefix(source, kind, placeholder) {
769
+ const { from, to } = lineBounds(source.value, source.start, source.end);
770
+ const block = source.value.slice(from, to);
771
+ const lines = block.split("\n");
772
+ const pattern = LINE_PREFIX_PATTERN[kind];
773
+ const isAlreadyApplied = lines.every((line) => pattern.test(line));
774
+ const next = lines.map((line, index) => {
775
+ const bare = line.replace(ANY_BLOCK_PREFIX, "");
776
+ if (isAlreadyApplied) return bare;
777
+ const text = bare || (lines.length === 1 ? placeholder : "");
778
+ if (kind === "heading2") return `## ${text}`;
779
+ if (kind === "heading3") return `### ${text}`;
780
+ if (kind === "bulletList") return `- ${text}`;
781
+ if (kind === "numberedList") return `${index + 1}. ${text}`;
782
+ return `> ${text}`;
783
+ });
784
+ const result = next.join("\n");
785
+ return replaceRange(source, from, to, result, [0, result.length]);
786
+ }
787
+ function insertLink(source, params) {
788
+ const label = params.text?.trim() || source.value.slice(source.start, source.end) || params.url;
789
+ const markdown = `[${label}](${params.url})`;
790
+ return replaceRange(source, source.start, source.end, markdown, [markdown.length, markdown.length]);
791
+ }
792
+ function insertImage(source, params) {
793
+ const markdown = `![${params.alt.replace(/[\][]/g, "")}](${params.url})`;
794
+ return replaceRange(source, source.start, source.end, markdown, [markdown.length, markdown.length]);
795
+ }
796
+ function isAbsoluteUrl(value) {
797
+ try {
798
+ const { protocol } = new URL(value.trim());
799
+ return protocol === "http:" || protocol === "https:";
800
+ } catch {
801
+ return false;
802
+ }
803
+ }
804
+
805
+ // src/components/EmojiPicker.tsx
806
+ import { useId, useState as useState4 } from "react";
807
+
808
+ // src/lib/emoji.ts
809
+ var EMOJI_CATEGORIES = [
810
+ "smileys",
811
+ "gestures",
812
+ "food",
813
+ "nature",
814
+ "travel",
815
+ "objects",
816
+ "symbols"
817
+ ];
818
+ function entries(raw) {
819
+ return raw.split("|").map((item) => {
820
+ const [char = "", keywords = ""] = item.split(":");
821
+ return { char, keywords };
822
+ });
823
+ }
824
+ var EMOJI_BY_CATEGORY = {
825
+ smileys: entries(
826
+ "\u{1F600}:sorriso smile happy feliz|\u{1F601}:alegre grin|\u{1F602}:rindo lol laugh|\u{1F60A}:feliz blush|\u{1F60D}:amei love apaixonado|\u{1F60E}:legal cool|\u{1F609}:piscada wink|\u{1F970}:carinho|\u{1F618}:beijo kiss|\u{1F914}:pensando think|\u{1F605}:aliviado|\u{1F622}:triste sad cry|\u{1F62D}:chorando|\u{1F621}:bravo angry|\u{1F634}:sono sleep|\u{1F929}:uau wow estrela|\u{1F642}:simples|\u{1F643}:invertido|\u{1F607}:anjo|\u{1F973}:festa party|\u{1F60B}:gostoso yum|\u{1F917}:abraco hug|\u{1F62E}:surpreso|\u{1F62C}:sem graca"
827
+ ),
828
+ gestures: entries(
829
+ "\u{1F44D}:joia like ok|\u{1F44E}:nao dislike|\u{1F44F}:palmas clap|\u{1F64C}:comemorar hooray|\u{1F64F}:obrigado por favor thanks pray|\u{1F4AA}:forca strong|\u{1F44B}:oi tchau wave|\u{1F91D}:acordo handshake|\u270C\uFE0F:paz peace|\u{1F44C}:perfeito|\u{1F449}:direita point|\u{1F447}:baixo|\u261D\uFE0F:cima|\u270D\uFE0F:escrever write|\u{1F91E}:torcendo"
830
+ ),
831
+ food: entries(
832
+ "\u{1F355}:pizza|\u{1F354}:hamburguer burger|\u{1F35F}:batata fritas|\u{1F32D}:cachorro quente|\u{1F363}:sushi|\u{1F35D}:massa pasta|\u{1F957}:salada salad|\u{1F370}:bolo cake|\u{1F36B}:chocolate|\u{1F377}:vinho wine|\u{1F37A}:cerveja beer|\u{1F379}:drink coquetel|\u2615:cafe coffee|\u{1F942}:brinde cheers|\u{1F34E}:maca apple|\u{1F353}:morango|\u{1F349}:melancia|\u{1F950}:croissant|\u{1F969}:carne steak|\u{1F366}:sorvete ice cream"
833
+ ),
834
+ nature: entries(
835
+ "\u{1F31E}:sol sun|\u{1F319}:lua moon|\u2B50:estrela star|\u{1F308}:arco-iris rainbow|\u{1F525}:fogo fire|\u{1F4A7}:agua water|\u{1F338}:flor flower|\u{1F339}:rosa|\u{1F333}:arvore tree|\u{1F334}:palmeira palm|\u{1F340}:trevo|\u{1F436}:cachorro dog|\u{1F431}:gato cat|\u{1F41F}:peixe fish|\u{1F98B}:borboleta"
836
+ ),
837
+ travel: entries(
838
+ "\u{1F697}:carro car|\u{1F68C}:onibus|\u2708\uFE0F:aviao plane|\u{1F6B2}:bicicleta|\u{1F3E0}:casa home|\u{1F3D6}\uFE0F:praia beach|\u{1F3DD}\uFE0F:ilha|\u{1F3E8}:hotel|\u{1F4CD}:local pin|\u{1F5FA}\uFE0F:mapa map|\u26F1\uFE0F:guarda-sol|\u{1F3A1}:roda gigante|\u{1F306}:cidade|\u{1F6CD}\uFE0F:compras shopping"
839
+ ),
840
+ objects: entries(
841
+ "\u{1F389}:festa celebracao party|\u{1F381}:presente gift|\u{1F382}:aniversario birthday|\u{1F3B6}:musica music|\u{1F4E3}:aviso megaphone|\u{1F4E2}:anuncio|\u{1F4C5}:calendario calendar data|\u23F0:horario clock|\u{1F4DE}:telefone phone|\u{1F4F1}:celular mobile|\u{1F4BB}:computador|\u{1F4F7}:foto camera|\u{1F39F}\uFE0F:ingresso ticket|\u{1F3C6}:trofeu trophy|\u{1F4A1}:ideia idea|\u{1F514}:sino bell|\u{1F4CC}:fixado|\u{1F511}:chave key"
842
+ ),
843
+ symbols: entries(
844
+ "\u2764\uFE0F:coracao heart amor|\u{1F49B}:amarelo|\u{1F499}:azul|\u{1F49A}:verde|\u2728:brilho sparkles novo|\u2705:ok check|\u274C:erro x|\u26A0\uFE0F:atencao warning|\u2757:importante|\u2753:pergunta|\u27A1\uFE0F:seta arrow|\u2B06\uFE0F:cima|\u{1F4AF}:cem 100|\u{1F195}:novo new|\u{1F51D}:topo|\u{1F4AC}:conversa chat|\u{1F4B0}:dinheiro money|\u{1F193}:gratis free|\u267B\uFE0F:reciclar"
845
+ )
846
+ };
847
+ function searchEmoji(query) {
848
+ const needle = query.trim().toLowerCase();
849
+ if (!needle) return [];
850
+ return EMOJI_CATEGORIES.flatMap((category) => EMOJI_BY_CATEGORY[category]).filter(
851
+ (entry) => entry.keywords.toLowerCase().includes(needle)
852
+ );
853
+ }
854
+
855
+ // src/components/EmojiPicker.tsx
856
+ import { jsx as jsx4, jsxs as jsxs2 } from "react/jsx-runtime";
857
+ var CATEGORY_MESSAGE = {
858
+ smileys: "emojiSmileys",
859
+ gestures: "emojiGestures",
860
+ food: "emojiFood",
861
+ nature: "emojiNature",
862
+ travel: "emojiTravel",
863
+ objects: "emojiObjects",
864
+ symbols: "emojiSymbols"
865
+ };
866
+ function EmojiPicker({ onPick, onClose }) {
867
+ const { messages } = useContentText();
868
+ const [category, setCategory] = useState4("smileys");
869
+ const [query, setQuery] = useState4("");
870
+ const searchId = useId();
871
+ const isSearching = query.trim().length > 0;
872
+ const visible = isSearching ? searchEmoji(query) : EMOJI_BY_CATEGORY[category];
873
+ return /* @__PURE__ */ jsxs2(
874
+ "div",
875
+ {
876
+ className: "adc-popover adc-emoji",
877
+ role: "dialog",
878
+ "aria-label": messages.emojiTitle,
879
+ onKeyDown: (event) => {
880
+ if (event.key !== "Escape") return;
881
+ event.stopPropagation();
882
+ onClose();
883
+ },
884
+ children: [
885
+ /* @__PURE__ */ jsx4("label", { htmlFor: searchId, className: "adc-visually-hidden", children: messages.emojiSearch }),
886
+ /* @__PURE__ */ jsx4(
887
+ "input",
888
+ {
889
+ id: searchId,
890
+ type: "text",
891
+ role: "searchbox",
892
+ autoFocus: true,
893
+ placeholder: messages.emojiSearch,
894
+ value: query,
895
+ onChange: (event) => setQuery(event.target.value),
896
+ onKeyDown: (event) => {
897
+ if (event.key === "Enter") event.preventDefault();
898
+ }
899
+ }
900
+ ),
901
+ !isSearching && /* @__PURE__ */ jsx4("div", { className: "adc-emoji-categories", role: "group", "aria-label": messages.emojiCategories, children: EMOJI_CATEGORIES.map((value) => /* @__PURE__ */ jsx4(
902
+ "button",
903
+ {
904
+ type: "button",
905
+ className: "adc-tab",
906
+ "aria-pressed": category === value,
907
+ onClick: () => setCategory(value),
908
+ children: messages[CATEGORY_MESSAGE[value]]
909
+ },
910
+ value
911
+ )) }),
912
+ visible.length === 0 ? /* @__PURE__ */ jsx4("p", { className: "adc-muted", role: "status", children: messages.emojiEmpty }) : /* @__PURE__ */ jsx4("div", { className: "adc-emoji-grid", children: visible.map((entry) => /* @__PURE__ */ jsx4(
913
+ "button",
914
+ {
915
+ type: "button",
916
+ className: "adc-emoji-button",
917
+ "aria-label": entry.keywords.split(" ")[0] ?? entry.char,
918
+ onClick: () => onPick(entry.char),
919
+ children: entry.char
920
+ },
921
+ entry.char
922
+ )) })
923
+ ]
924
+ }
925
+ );
926
+ }
927
+
928
+ // src/components/InsertDialog.tsx
929
+ import { useId as useId2, useState as useState5 } from "react";
930
+ import { jsx as jsx5, jsxs as jsxs3 } from "react/jsx-runtime";
931
+ function InsertDialog(props) {
932
+ const { messages } = useContentText();
933
+ const [url, setUrl] = useState5("");
934
+ const [text, setText] = useState5(props.initialText);
935
+ const [errorMessage, setErrorMessage] = useState5("");
936
+ const urlId = useId2();
937
+ const textId = useId2();
938
+ const isImage = props.kind === "image";
939
+ function submit() {
940
+ if (!isAbsoluteUrl(url)) return setErrorMessage(messages.errorUrl);
941
+ if (props.kind === "image") props.onSubmit({ url: url.trim(), alt: text });
942
+ else props.onSubmit({ url: url.trim(), text });
943
+ }
944
+ async function handlePick(file) {
945
+ if (props.kind !== "image" || !props.onUpload) return;
946
+ setErrorMessage("");
947
+ const result = await props.onUpload(file);
948
+ if ("error" in result) return setErrorMessage(messages[result.error]);
949
+ setUrl(result.url);
950
+ }
951
+ function handleKeyDown(event) {
952
+ if (event.key === "Escape") {
953
+ event.stopPropagation();
954
+ props.onClose();
955
+ }
956
+ if (event.key === "Enter" && event.target instanceof HTMLInputElement) {
957
+ event.preventDefault();
958
+ submit();
959
+ }
960
+ }
961
+ return /* @__PURE__ */ jsxs3(
962
+ "div",
963
+ {
964
+ className: "adc-popover adc-insert",
965
+ role: "dialog",
966
+ "aria-label": isImage ? messages.imageDialogTitle : messages.linkDialogTitle,
967
+ onKeyDown: handleKeyDown,
968
+ children: [
969
+ isImage && props.onUpload && /* @__PURE__ */ jsx5(
970
+ FilePicker,
971
+ {
972
+ buttonLabel: props.isUploading ? messages.coverUploading : messages.imageUploadFromDevice,
973
+ emptyLabel: messages.fileNoneChosen,
974
+ accept: "image/*",
975
+ isBusy: props.isUploading,
976
+ onPick: (file) => void handlePick(file)
977
+ }
978
+ ),
979
+ /* @__PURE__ */ jsxs3("div", { className: "adc-field", children: [
980
+ /* @__PURE__ */ jsx5("label", { htmlFor: urlId, children: isImage ? messages.fieldCoverUrl : messages.linkUrl }),
981
+ /* @__PURE__ */ jsx5(
982
+ "input",
983
+ {
984
+ id: urlId,
985
+ type: "url",
986
+ autoFocus: true,
987
+ placeholder: "https://",
988
+ value: url,
989
+ onChange: (event) => setUrl(event.target.value)
990
+ }
991
+ )
992
+ ] }),
993
+ /* @__PURE__ */ jsxs3("div", { className: "adc-field", children: [
994
+ /* @__PURE__ */ jsx5("label", { htmlFor: textId, children: isImage ? messages.fieldCoverAlt : messages.linkText }),
995
+ /* @__PURE__ */ jsx5("input", { id: textId, type: "text", value: text, onChange: (event) => setText(event.target.value) })
996
+ ] }),
997
+ /* @__PURE__ */ jsx5("p", { className: "adc-error", role: "alert", hidden: !errorMessage, children: errorMessage }),
998
+ /* @__PURE__ */ jsxs3("div", { className: "adc-insert-actions", children: [
999
+ /* @__PURE__ */ jsx5("button", { type: "button", className: "adc-button adc-button--ghost", onClick: props.onClose, children: messages.dialogCancel }),
1000
+ /* @__PURE__ */ jsx5(
1001
+ "button",
1002
+ {
1003
+ type: "button",
1004
+ className: "adc-button adc-button--primary",
1005
+ disabled: isImage && props.isUploading,
1006
+ onClick: submit,
1007
+ children: messages.dialogInsert
1008
+ }
1009
+ )
1010
+ ] })
1011
+ ]
1012
+ }
1013
+ );
1014
+ }
1015
+
1016
+ // src/components/Tooltip.tsx
1017
+ import { useId as useId3, useState as useState6 } from "react";
1018
+ import { jsx as jsx6, jsxs as jsxs4 } from "react/jsx-runtime";
1019
+ function Tooltip({ text, children }) {
1020
+ const id = useId3();
1021
+ const [isHovered, setIsHovered] = useState6(false);
1022
+ const [isFocused, setIsFocused] = useState6(false);
1023
+ return /* @__PURE__ */ jsxs4(
1024
+ "span",
1025
+ {
1026
+ className: "adc-tip",
1027
+ onMouseEnter: () => setIsHovered(true),
1028
+ onMouseLeave: () => setIsHovered(false),
1029
+ onFocus: () => setIsFocused(true),
1030
+ onBlur: () => setIsFocused(false),
1031
+ onKeyDown: (event) => {
1032
+ if (event.key !== "Escape" || !(isHovered || isFocused)) return;
1033
+ setIsHovered(false);
1034
+ setIsFocused(false);
1035
+ },
1036
+ children: [
1037
+ /* @__PURE__ */ jsx6("span", { "aria-describedby": id, className: "adc-tip-target", children }),
1038
+ /* @__PURE__ */ jsx6("span", { id, role: "tooltip", className: "adc-tooltip", "data-visible": isHovered || isFocused, children: text })
1039
+ ]
1040
+ }
1041
+ );
1042
+ }
1043
+
1044
+ // src/components/MarkdownEditor.tsx
1045
+ import { jsx as jsx7, jsxs as jsxs5 } from "react/jsx-runtime";
1046
+ var SIMPLE_ACTIONS = [
1047
+ { id: "bold", icon: Bold, label: "formatBold", shortcut: "B" },
1048
+ { id: "italic", icon: Italic, label: "formatItalic", shortcut: "I" },
1049
+ { id: "heading2", icon: Heading2, label: "formatHeading2" },
1050
+ { id: "heading3", icon: Heading3, label: "formatHeading3" },
1051
+ { id: "bulletList", icon: List, label: "formatBulletList" },
1052
+ { id: "numberedList", icon: ListOrdered, label: "formatNumberedList" },
1053
+ { id: "quote", icon: Quote, label: "formatQuote" }
1054
+ ];
1055
+ function ToolButton({ icon: Icon, text, isExpanded, onClick }) {
1056
+ return /* @__PURE__ */ jsx7(Tooltip, { text, children: /* @__PURE__ */ jsx7(
1057
+ "button",
1058
+ {
1059
+ type: "button",
1060
+ className: "adc-tool",
1061
+ "aria-label": text,
1062
+ ...isExpanded === void 0 ? {} : { "aria-expanded": isExpanded },
1063
+ onClick,
1064
+ children: /* @__PURE__ */ jsx7(Icon, { "aria-hidden": "true", className: "adc-icon" })
1065
+ }
1066
+ ) });
1067
+ }
1068
+ function MarkdownEditor({
1069
+ value,
1070
+ onChange,
1071
+ labelledBy,
1072
+ describedBy,
1073
+ showToolbar = true,
1074
+ onUploadImage,
1075
+ isUploading = false
1076
+ }) {
1077
+ const { messages } = useContentText();
1078
+ const textareaRef = useRef3(null);
1079
+ const pendingSelection = useRef3(void 0);
1080
+ const savedSelection = useRef3({ value, start: value.length, end: value.length });
1081
+ const [panel, setPanel] = useState7();
1082
+ useLayoutEffect(() => {
1083
+ const pending = pendingSelection.current;
1084
+ const textarea = textareaRef.current;
1085
+ if (!pending || !textarea) return;
1086
+ pendingSelection.current = void 0;
1087
+ textarea.focus();
1088
+ textarea.setSelectionRange(pending.start, pending.end);
1089
+ }, [value]);
1090
+ function readSelection() {
1091
+ const textarea = textareaRef.current;
1092
+ return { value, start: textarea?.selectionStart ?? value.length, end: textarea?.selectionEnd ?? value.length };
1093
+ }
1094
+ function apply(next) {
1095
+ pendingSelection.current = { start: next.start, end: next.end };
1096
+ onChange(next.value);
1097
+ setPanel(void 0);
1098
+ }
1099
+ function run(id) {
1100
+ const selection = readSelection();
1101
+ const sample = messages.formatSampleText;
1102
+ if (id === "bold") return apply(toggleWrap(selection, "**", sample));
1103
+ if (id === "italic") return apply(toggleWrap(selection, "*", sample));
1104
+ apply(toggleLinePrefix(selection, id, sample));
1105
+ }
1106
+ function openPanel(next) {
1107
+ if (panel === next) return setPanel(void 0);
1108
+ savedSelection.current = readSelection();
1109
+ setPanel(next);
1110
+ }
1111
+ function closePanel() {
1112
+ setPanel(void 0);
1113
+ textareaRef.current?.focus();
1114
+ }
1115
+ function handleKeyDown(event) {
1116
+ if (!showToolbar || !(event.ctrlKey || event.metaKey) || event.altKey) return;
1117
+ const key = event.key.toLowerCase();
1118
+ if (key !== "b" && key !== "i" && key !== "k") return;
1119
+ event.preventDefault();
1120
+ if (key === "k") return openPanel("link");
1121
+ run(key === "b" ? "bold" : "italic");
1122
+ }
1123
+ const saved = savedSelection.current;
1124
+ const selectedText = saved.value.slice(saved.start, saved.end);
1125
+ return /* @__PURE__ */ jsxs5("div", { className: "adc-md-editor", children: [
1126
+ showToolbar && /* @__PURE__ */ jsxs5("div", { className: "adc-md-toolbar", role: "toolbar", "aria-label": messages.toolbarLabel, children: [
1127
+ SIMPLE_ACTIONS.map(({ id, icon, label, shortcut }) => /* @__PURE__ */ jsx7(
1128
+ ToolButton,
1129
+ {
1130
+ icon,
1131
+ text: shortcut ? `${messages[label]} (Ctrl+${shortcut})` : messages[label],
1132
+ onClick: () => run(id)
1133
+ },
1134
+ id
1135
+ )),
1136
+ /* @__PURE__ */ jsx7(
1137
+ ToolButton,
1138
+ {
1139
+ icon: LinkIcon,
1140
+ text: `${messages.formatLink} (Ctrl+K)`,
1141
+ isExpanded: panel === "link",
1142
+ onClick: () => openPanel("link")
1143
+ }
1144
+ ),
1145
+ /* @__PURE__ */ jsx7(
1146
+ ToolButton,
1147
+ {
1148
+ icon: ImageIcon,
1149
+ text: messages.formatImage,
1150
+ isExpanded: panel === "image",
1151
+ onClick: () => openPanel("image")
1152
+ }
1153
+ ),
1154
+ /* @__PURE__ */ jsx7(
1155
+ ToolButton,
1156
+ {
1157
+ icon: Smile,
1158
+ text: messages.formatEmoji,
1159
+ isExpanded: panel === "emoji",
1160
+ onClick: () => openPanel("emoji")
1161
+ }
1162
+ )
1163
+ ] }),
1164
+ panel === "link" && /* @__PURE__ */ jsx7(
1165
+ InsertDialog,
1166
+ {
1167
+ kind: "link",
1168
+ initialText: selectedText,
1169
+ onClose: closePanel,
1170
+ onSubmit: (values) => apply(insertLink(saved, values))
1171
+ }
1172
+ ),
1173
+ panel === "image" && /* @__PURE__ */ jsx7(
1174
+ InsertDialog,
1175
+ {
1176
+ kind: "image",
1177
+ initialText: "",
1178
+ isUploading,
1179
+ ...onUploadImage ? { onUpload: onUploadImage } : {},
1180
+ onClose: closePanel,
1181
+ onSubmit: (values) => apply(insertImage(saved, values))
1182
+ }
1183
+ ),
1184
+ panel === "emoji" && /* @__PURE__ */ jsx7(EmojiPicker, { onClose: closePanel, onPick: (emoji) => apply(insertText(saved, emoji)) }),
1185
+ /* @__PURE__ */ jsx7(
1186
+ "textarea",
1187
+ {
1188
+ ref: textareaRef,
1189
+ "aria-labelledby": labelledBy,
1190
+ ...describedBy ? { "aria-describedby": describedBy } : {},
1191
+ className: "adc-markdown-input",
1192
+ value,
1193
+ onChange: (event) => onChange(event.target.value),
1194
+ onKeyDown: handleKeyDown
1195
+ }
1196
+ )
1197
+ ] });
1198
+ }
1199
+
1200
+ // src/components/StatusChip.tsx
1201
+ import { POST_STATUS } from "@adatechnology/content-contracts";
1202
+ import { Archive, CalendarClock, CircleCheck, PencilLine } from "lucide-react";
1203
+ import { jsx as jsx8, jsxs as jsxs6 } from "react/jsx-runtime";
1204
+ var STATUS_VIEW = {
1205
+ [POST_STATUS.DRAFT]: { icon: PencilLine, label: "statusDraft" },
1206
+ [POST_STATUS.SCHEDULED]: { icon: CalendarClock, label: "statusScheduled" },
1207
+ [POST_STATUS.PUBLISHED]: { icon: CircleCheck, label: "statusPublished" },
1208
+ [POST_STATUS.ARCHIVED]: { icon: Archive, label: "statusArchived" }
1209
+ };
1210
+ function StatusChip({ status }) {
1211
+ const { messages } = useContentText();
1212
+ const { icon: Icon, label } = STATUS_VIEW[status];
1213
+ return /* @__PURE__ */ jsxs6("span", { className: `adc-chip adc-chip--${status}`, children: [
1214
+ /* @__PURE__ */ jsx8(Icon, { "aria-hidden": "true", className: "adc-icon" }),
1215
+ messages[label]
1216
+ ] });
1217
+ }
1218
+
1219
+ // src/components/TagsInput.tsx
1220
+ import { normalizeTags, TAGS_MAX_COUNT } from "@adatechnology/content-contracts";
1221
+ import { X } from "lucide-react";
1222
+ import { useId as useId4, useState as useState8 } from "react";
1223
+ import { jsx as jsx9, jsxs as jsxs7 } from "react/jsx-runtime";
1224
+ function TagsInput({ value, onChange, suggestions = [], label }) {
1225
+ const { messages, format } = useContentText();
1226
+ const [text, setText] = useState8("");
1227
+ const inputId = useId4();
1228
+ const listId = useId4();
1229
+ function commit(raw) {
1230
+ const added = splitTagInput(raw);
1231
+ if (added.length > 0) onChange(normalizeTags([...value, ...added]));
1232
+ setText("");
1233
+ }
1234
+ function handleKeyDown(event) {
1235
+ if (event.key === "Enter" || event.key === ",") {
1236
+ event.preventDefault();
1237
+ commit(text);
1238
+ } else if (event.key === "Backspace" && !text && value.length > 0) {
1239
+ onChange(value.slice(0, -1));
1240
+ }
1241
+ }
1242
+ return /* @__PURE__ */ jsxs7("div", { className: "adc-field", children: [
1243
+ /* @__PURE__ */ jsx9("label", { htmlFor: inputId, children: label }),
1244
+ /* @__PURE__ */ jsxs7("div", { className: "adc-tags-input", children: [
1245
+ value.map((tag) => /* @__PURE__ */ jsxs7("span", { className: "adc-tag", children: [
1246
+ tag,
1247
+ /* @__PURE__ */ jsx9(
1248
+ "button",
1249
+ {
1250
+ type: "button",
1251
+ className: "adc-tag-remove",
1252
+ "aria-label": format("tagRemove", { tag }),
1253
+ onClick: () => onChange(value.filter((current) => current !== tag)),
1254
+ children: /* @__PURE__ */ jsx9(X, { "aria-hidden": "true", className: "adc-icon" })
1255
+ }
1256
+ )
1257
+ ] }, tag)),
1258
+ /* @__PURE__ */ jsx9(
1259
+ "input",
1260
+ {
1261
+ id: inputId,
1262
+ value: text,
1263
+ list: suggestions.length > 0 ? listId : void 0,
1264
+ disabled: value.length >= TAGS_MAX_COUNT,
1265
+ onChange: (event) => setText(event.target.value),
1266
+ onKeyDown: handleKeyDown,
1267
+ onBlur: () => commit(text),
1268
+ "aria-describedby": `${inputId}-hint`
1269
+ }
1270
+ )
1271
+ ] }),
1272
+ /* @__PURE__ */ jsx9("small", { id: `${inputId}-hint`, className: "adc-hint", children: messages.tagsHint }),
1273
+ suggestions.length > 0 && /* @__PURE__ */ jsx9("datalist", { id: listId, children: suggestions.filter((tag) => !value.includes(tag)).map((tag) => /* @__PURE__ */ jsx9("option", { value: tag }, tag)) })
1274
+ ] });
1275
+ }
1276
+
1277
+ // src/components/PostEditor.tsx
1278
+ import { jsx as jsx10, jsxs as jsxs8 } from "react/jsx-runtime";
1279
+ function TextField({ label, value, onChange, error, hint, type = "text", multiline, maxLength }) {
1280
+ const id = useId5();
1281
+ const describedBy = [hint ? `${id}-hint` : "", error ? `${id}-error` : ""].filter(Boolean).join(" ") || void 0;
1282
+ const common = {
1283
+ id,
1284
+ value,
1285
+ maxLength,
1286
+ "aria-invalid": error ? true : void 0,
1287
+ "aria-describedby": describedBy
1288
+ };
1289
+ return /* @__PURE__ */ jsxs8("div", { className: "adc-field", children: [
1290
+ /* @__PURE__ */ jsx10("label", { htmlFor: id, children: label }),
1291
+ multiline ? /* @__PURE__ */ jsx10("textarea", { ...common, rows: 3, onChange: (event) => onChange(event.target.value) }) : /* @__PURE__ */ jsx10("input", { ...common, type, onChange: (event) => onChange(event.target.value) }),
1292
+ hint && /* @__PURE__ */ jsx10("small", { id: `${id}-hint`, className: "adc-hint", children: hint }),
1293
+ error && /* @__PURE__ */ jsx10("small", { id: `${id}-error`, className: "adc-error", children: error })
1294
+ ] });
1295
+ }
1296
+ function Section({ title, children }) {
1297
+ return /* @__PURE__ */ jsxs8("fieldset", { className: "adc-section", children: [
1298
+ /* @__PURE__ */ jsx10("legend", { children: title }),
1299
+ children
1300
+ ] });
1301
+ }
1302
+ function PostEditor({
1303
+ postId,
1304
+ defaults,
1305
+ onSaved,
1306
+ onArchived,
1307
+ onClose,
1308
+ showFormattingToolbar = true,
1309
+ renderDateTimeInput
1310
+ }) {
1311
+ const { messages, locale, format } = useContentText();
1312
+ const editor = usePostEditor({
1313
+ ...postId ? { postId } : {},
1314
+ ...defaults ? { defaults } : {},
1315
+ ...onSaved ? { onSaved } : {},
1316
+ ...onArchived ? { onArchived } : {}
1317
+ });
1318
+ const { confirmLeave } = useUnsavedChangesGuard(editor.isDirty, messages.unsavedConfirm);
1319
+ const [tab, setTab] = useState9("write");
1320
+ const bodyId = useId5();
1321
+ const scheduleId = useId5();
1322
+ const { draft, update, errors, post } = editor;
1323
+ if (editor.isLoading) {
1324
+ return /* @__PURE__ */ jsx10("p", { className: "adc-root adc-state", role: "status", children: messages.loading });
1325
+ }
1326
+ const status = post?.status;
1327
+ const isLive = status === "published" || status === "scheduled";
1328
+ return /* @__PURE__ */ jsxs8(
1329
+ "form",
1330
+ {
1331
+ className: "adc-root adc-editor",
1332
+ onSubmit: (event) => {
1333
+ event.preventDefault();
1334
+ void editor.save();
1335
+ },
1336
+ children: [
1337
+ /* @__PURE__ */ jsxs8("header", { className: "adc-toolbar", children: [
1338
+ onClose && /* @__PURE__ */ jsxs8("button", { type: "button", className: "adc-button adc-button--ghost", onClick: () => confirmLeave() && onClose(), children: [
1339
+ /* @__PURE__ */ jsx10(ArrowLeft, { "aria-hidden": "true", className: "adc-icon" }),
1340
+ messages.close
1341
+ ] }),
1342
+ /* @__PURE__ */ jsx10("h2", { className: "adc-title", children: post ? messages.editorEditTitle : messages.editorNewTitle }),
1343
+ status && /* @__PURE__ */ jsx10(StatusChip, { status }),
1344
+ editor.isDirty && /* @__PURE__ */ jsx10("span", { className: "adc-badge", children: messages.unsavedBadge })
1345
+ ] }),
1346
+ /* @__PURE__ */ jsxs8("div", { className: "adc-editor-grid", children: [
1347
+ /* @__PURE__ */ jsxs8("div", { className: "adc-editor-main", children: [
1348
+ /* @__PURE__ */ jsx10(
1349
+ TextField,
1350
+ {
1351
+ label: messages.fieldTitle,
1352
+ value: draft.title,
1353
+ maxLength: 200,
1354
+ onChange: (value) => update("title", value),
1355
+ error: errors.title ? messages.errorTitle : void 0
1356
+ }
1357
+ ),
1358
+ /* @__PURE__ */ jsx10(
1359
+ TextField,
1360
+ {
1361
+ label: messages.fieldSlug,
1362
+ value: draft.slug,
1363
+ maxLength: 120,
1364
+ hint: messages.fieldSlugHint,
1365
+ onChange: (value) => update("slug", value.toLowerCase()),
1366
+ error: errors.slug ? messages.errorSlug : void 0
1367
+ }
1368
+ ),
1369
+ /* @__PURE__ */ jsx10(
1370
+ TextField,
1371
+ {
1372
+ label: messages.fieldExcerpt,
1373
+ value: draft.excerpt,
1374
+ maxLength: 500,
1375
+ multiline: true,
1376
+ onChange: (value) => update("excerpt", value)
1377
+ }
1378
+ ),
1379
+ /* @__PURE__ */ jsxs8("div", { className: "adc-field", children: [
1380
+ /* @__PURE__ */ jsxs8("div", { className: "adc-tabs", role: "tablist", "aria-label": messages.fieldBody, children: [
1381
+ /* @__PURE__ */ jsx10("span", { className: "adc-label", id: `${bodyId}-label`, children: messages.fieldBody }),
1382
+ ["write", "preview"].map((value) => /* @__PURE__ */ jsx10(
1383
+ "button",
1384
+ {
1385
+ type: "button",
1386
+ role: "tab",
1387
+ "aria-selected": tab === value,
1388
+ "aria-controls": `${bodyId}-${value}`,
1389
+ className: "adc-tab",
1390
+ onClick: () => setTab(value),
1391
+ children: value === "write" ? messages.tabWrite : messages.tabPreview
1392
+ },
1393
+ value
1394
+ ))
1395
+ ] }),
1396
+ /* @__PURE__ */ jsxs8("div", { className: `adc-body-panes adc-body-panes--${tab}`, children: [
1397
+ /* @__PURE__ */ jsxs8("div", { id: `${bodyId}-write`, role: "tabpanel", className: "adc-pane adc-pane--write", children: [
1398
+ /* @__PURE__ */ jsx10(
1399
+ MarkdownEditor,
1400
+ {
1401
+ value: draft.body,
1402
+ onChange: (value) => update("body", value),
1403
+ labelledBy: `${bodyId}-label`,
1404
+ describedBy: `${bodyId}-hint`,
1405
+ showToolbar: showFormattingToolbar,
1406
+ isUploading: editor.isUploading,
1407
+ ...editor.canUploadCover ? { onUploadImage: editor.uploadImage } : {}
1408
+ }
1409
+ ),
1410
+ /* @__PURE__ */ jsx10("small", { id: `${bodyId}-hint`, className: "adc-hint", children: showFormattingToolbar ? messages.bodyHintToolbar : messages.bodyHint })
1411
+ ] }),
1412
+ /* @__PURE__ */ jsx10("div", { id: `${bodyId}-preview`, role: "tabpanel", className: "adc-pane adc-pane--preview", "aria-live": "polite", children: draft.body.trim() ? /* @__PURE__ */ jsx10(MarkdownContent, { markdown: draft.body, headingLevelOffset: 1 }) : /* @__PURE__ */ jsx10("p", { className: "adc-muted", children: messages.previewEmpty }) })
1413
+ ] })
1414
+ ] })
1415
+ ] }),
1416
+ /* @__PURE__ */ jsxs8("aside", { className: "adc-editor-side", children: [
1417
+ /* @__PURE__ */ jsxs8(Section, { title: messages.publishSection, children: [
1418
+ post?.publishedAt && /* @__PURE__ */ jsx10("p", { className: "adc-muted", children: format(status === "scheduled" ? "scheduledFor" : "publishedOn", {
1419
+ date: formatPostDate(post.publishedAt, locale, true)
1420
+ }) }),
1421
+ /* @__PURE__ */ jsxs8("button", { type: "submit", className: "adc-button", disabled: editor.isBusy, children: [
1422
+ /* @__PURE__ */ jsx10(Save, { "aria-hidden": "true", className: "adc-icon" }),
1423
+ editor.isBusy ? messages.saving : isLive ? messages.saveChanges : messages.save
1424
+ ] }),
1425
+ status !== "published" && /* @__PURE__ */ jsxs8(
1426
+ "button",
1427
+ {
1428
+ type: "button",
1429
+ className: "adc-button adc-button--primary",
1430
+ disabled: editor.isBusy,
1431
+ onClick: () => void editor.publishNow(),
1432
+ children: [
1433
+ /* @__PURE__ */ jsx10(Send, { "aria-hidden": "true", className: "adc-icon" }),
1434
+ messages.publishNow
1435
+ ]
1436
+ }
1437
+ ),
1438
+ renderDateTimeInput ? renderDateTimeInput({
1439
+ id: scheduleId,
1440
+ label: messages.scheduleAt,
1441
+ value: editor.scheduleAt,
1442
+ onChange: editor.setScheduleAt
1443
+ }) : /* @__PURE__ */ jsxs8("div", { className: "adc-field", children: [
1444
+ /* @__PURE__ */ jsx10("label", { htmlFor: scheduleId, children: messages.scheduleAt }),
1445
+ /* @__PURE__ */ jsx10(
1446
+ "input",
1447
+ {
1448
+ id: scheduleId,
1449
+ type: "datetime-local",
1450
+ value: editor.scheduleAt,
1451
+ onChange: (event) => editor.setScheduleAt(event.target.value)
1452
+ }
1453
+ )
1454
+ ] }),
1455
+ /* @__PURE__ */ jsxs8(
1456
+ "button",
1457
+ {
1458
+ type: "button",
1459
+ className: "adc-button",
1460
+ disabled: editor.isBusy || !editor.scheduleAt,
1461
+ onClick: () => void editor.schedule(),
1462
+ children: [
1463
+ /* @__PURE__ */ jsx10(CalendarClock2, { "aria-hidden": "true", className: "adc-icon" }),
1464
+ messages.schedule
1465
+ ]
1466
+ }
1467
+ ),
1468
+ isLive && /* @__PURE__ */ jsxs8(
1469
+ "button",
1470
+ {
1471
+ type: "button",
1472
+ className: "adc-button",
1473
+ disabled: editor.isBusy,
1474
+ onClick: () => void editor.unpublish(),
1475
+ children: [
1476
+ /* @__PURE__ */ jsx10(EyeOff, { "aria-hidden": "true", className: "adc-icon" }),
1477
+ messages.unpublish
1478
+ ]
1479
+ }
1480
+ ),
1481
+ post && status !== "archived" && /* @__PURE__ */ jsxs8(
1482
+ "button",
1483
+ {
1484
+ type: "button",
1485
+ className: "adc-button adc-button--danger",
1486
+ disabled: editor.isBusy,
1487
+ onClick: () => window.confirm(messages.archiveConfirm) && void editor.archive(),
1488
+ children: [
1489
+ /* @__PURE__ */ jsx10(Archive2, { "aria-hidden": "true", className: "adc-icon" }),
1490
+ messages.archive
1491
+ ]
1492
+ }
1493
+ ),
1494
+ editor.feedback && /* @__PURE__ */ jsx10(
1495
+ "p",
1496
+ {
1497
+ className: editor.feedback === "saved" ? "adc-success" : "adc-error",
1498
+ role: editor.feedback === "saved" ? "status" : "alert",
1499
+ children: messages[editor.feedback]
1500
+ }
1501
+ )
1502
+ ] }),
1503
+ /* @__PURE__ */ jsxs8(Section, { title: messages.fieldCover, children: [
1504
+ draft.coverImageUrl && /* @__PURE__ */ jsx10("img", { className: "adc-cover-preview", src: draft.coverImageUrl, alt: draft.coverImageAlt }),
1505
+ editor.canUploadCover && /* @__PURE__ */ jsx10(
1506
+ FilePicker,
1507
+ {
1508
+ buttonLabel: editor.isUploading ? messages.coverUploading : messages.coverUpload,
1509
+ emptyLabel: messages.fileNoneChosen,
1510
+ accept: "image/jpeg,image/png,image/webp",
1511
+ isBusy: editor.isUploading,
1512
+ onPick: (file) => void editor.uploadCover(file)
1513
+ }
1514
+ ),
1515
+ /* @__PURE__ */ jsx10(
1516
+ TextField,
1517
+ {
1518
+ label: messages.fieldCoverUrl,
1519
+ type: "url",
1520
+ value: draft.coverImageUrl,
1521
+ onChange: (value) => update("coverImageUrl", value),
1522
+ error: errors.coverImageUrl ? messages.errorUrl : void 0
1523
+ }
1524
+ ),
1525
+ /* @__PURE__ */ jsx10(
1526
+ TextField,
1527
+ {
1528
+ label: messages.fieldCoverAlt,
1529
+ value: draft.coverImageAlt,
1530
+ maxLength: 300,
1531
+ onChange: (value) => update("coverImageAlt", value)
1532
+ }
1533
+ ),
1534
+ draft.coverImageUrl && /* @__PURE__ */ jsxs8(
1535
+ "button",
1536
+ {
1537
+ type: "button",
1538
+ className: "adc-button adc-button--ghost",
1539
+ onClick: () => update("coverImageUrl", ""),
1540
+ children: [
1541
+ /* @__PURE__ */ jsx10(Trash2, { "aria-hidden": "true", className: "adc-icon" }),
1542
+ messages.coverRemove
1543
+ ]
1544
+ }
1545
+ )
1546
+ ] }),
1547
+ /* @__PURE__ */ jsxs8(Section, { title: messages.fieldTags, children: [
1548
+ /* @__PURE__ */ jsx10(
1549
+ TagsInput,
1550
+ {
1551
+ label: messages.fieldTags,
1552
+ value: draft.tags,
1553
+ suggestions: editor.tagSuggestions,
1554
+ onChange: (tags) => update("tags", tags)
1555
+ }
1556
+ ),
1557
+ /* @__PURE__ */ jsx10(
1558
+ TextField,
1559
+ {
1560
+ label: messages.fieldAuthor,
1561
+ value: draft.authorName,
1562
+ maxLength: 120,
1563
+ onChange: (value) => update("authorName", value)
1564
+ }
1565
+ )
1566
+ ] }),
1567
+ /* @__PURE__ */ jsxs8(Section, { title: messages.seoSection, children: [
1568
+ /* @__PURE__ */ jsx10(
1569
+ TextField,
1570
+ {
1571
+ label: messages.fieldSeoTitle,
1572
+ value: draft.seoTitle,
1573
+ maxLength: 200,
1574
+ onChange: (value) => update("seoTitle", value)
1575
+ }
1576
+ ),
1577
+ /* @__PURE__ */ jsx10(
1578
+ TextField,
1579
+ {
1580
+ label: messages.fieldSeoDescription,
1581
+ value: draft.seoDescription,
1582
+ maxLength: 320,
1583
+ multiline: true,
1584
+ onChange: (value) => update("seoDescription", value)
1585
+ }
1586
+ ),
1587
+ /* @__PURE__ */ jsx10(
1588
+ TextField,
1589
+ {
1590
+ label: messages.fieldCanonical,
1591
+ type: "url",
1592
+ value: draft.canonicalUrl,
1593
+ onChange: (value) => update("canonicalUrl", value),
1594
+ error: errors.canonicalUrl ? messages.errorUrl : void 0
1595
+ }
1596
+ )
1597
+ ] })
1598
+ ] })
1599
+ ] })
1600
+ ]
1601
+ }
1602
+ );
1603
+ }
1604
+
1605
+ // src/components/PostList.tsx
1606
+ import { POST_STATUSES } from "@adatechnology/content-contracts";
1607
+ import { Plus, RotateCcw, Search } from "lucide-react";
1608
+ import { useId as useId6 } from "react";
1609
+
1610
+ // src/hooks/usePostList.ts
1611
+ import { useState as useState10 } from "react";
1612
+ function usePostList(params) {
1613
+ const api = useContentAdminApi();
1614
+ const [filters, setFilters] = useState10({});
1615
+ const [page, setPage] = useState10(1);
1616
+ const key = JSON.stringify({ filters, page, pageSize: params.pageSize, reload: params.reloadKey ?? 0 });
1617
+ const posts = useAsyncResource(() => api.listPosts({ ...filters, page, pageSize: params.pageSize }), key);
1618
+ const tags = useAsyncResource(
1619
+ () => api.listTags ? api.listTags() : Promise.resolve([]),
1620
+ `tags-${params.reloadKey ?? 0}`
1621
+ );
1622
+ function updateFilters(next) {
1623
+ setFilters(next);
1624
+ setPage(1);
1625
+ }
1626
+ return {
1627
+ posts,
1628
+ tags: api.listTags ? tags.data ?? [] : void 0,
1629
+ filters,
1630
+ updateFilters,
1631
+ page,
1632
+ setPage,
1633
+ hasFilters: Boolean(filters.status || filters.tag || filters.search)
1634
+ };
1635
+ }
1636
+
1637
+ // src/components/Pagination.tsx
1638
+ import { ChevronLeft, ChevronRight } from "lucide-react";
1639
+
1640
+ // src/lib/pagination.ts
1641
+ function buildPageItems(params) {
1642
+ const siblings = params.siblings ?? 1;
1643
+ const total = Math.max(1, params.total);
1644
+ const current = Math.min(Math.max(1, params.current), total);
1645
+ const pages = /* @__PURE__ */ new Set([1, total]);
1646
+ for (let page = current - siblings; page <= current + siblings; page += 1) {
1647
+ if (page >= 1 && page <= total) pages.add(page);
1648
+ }
1649
+ const items = [];
1650
+ let previous = 0;
1651
+ for (const page of [...pages].sort((left, right) => left - right)) {
1652
+ if (page - previous > 1) items.push({ kind: "gap", key: `gap-${previous}` });
1653
+ items.push({ kind: "page", page });
1654
+ previous = page;
1655
+ }
1656
+ return items;
1657
+ }
1658
+
1659
+ // src/components/Pagination.tsx
1660
+ import { jsx as jsx11, jsxs as jsxs9 } from "react/jsx-runtime";
1661
+ function Pagination({ page, totalPages, getPageHref, onPageChange }) {
1662
+ const { messages, format } = useContentText();
1663
+ const renderLink = useRenderLink();
1664
+ if (totalPages <= 1) return null;
1665
+ function renderTarget(target, label, content, isCurrent = false) {
1666
+ const className = `adc-page${isCurrent ? " adc-page--current" : ""}`;
1667
+ if (getPageHref && !isCurrent)
1668
+ return renderLink({ href: getPageHref(target), className, "aria-label": label, children: content });
1669
+ return /* @__PURE__ */ jsx11(
1670
+ "button",
1671
+ {
1672
+ type: "button",
1673
+ className,
1674
+ "aria-label": label,
1675
+ "aria-current": isCurrent ? "page" : void 0,
1676
+ disabled: isCurrent,
1677
+ onClick: () => onPageChange?.(target),
1678
+ children: content
1679
+ }
1680
+ );
1681
+ }
1682
+ return /* @__PURE__ */ jsxs9("nav", { className: "adc-pagination", "aria-label": messages.paginationLabel, children: [
1683
+ page > 1 && renderTarget(page - 1, messages.paginationPrevious, /* @__PURE__ */ jsx11(ChevronLeft, { "aria-hidden": "true", className: "adc-icon" })),
1684
+ buildPageItems({ current: page, total: totalPages }).map(
1685
+ (item) => item.kind === "gap" ? /* @__PURE__ */ jsx11("span", { className: "adc-page-gap", "aria-hidden": "true", children: "\u2026" }, item.key) : /* @__PURE__ */ jsx11("span", { children: renderTarget(item.page, format("pageLabel", { page: item.page }), item.page, item.page === page) }, item.page)
1686
+ ),
1687
+ page < totalPages && renderTarget(page + 1, messages.paginationNext, /* @__PURE__ */ jsx11(ChevronRight, { "aria-hidden": "true", className: "adc-icon" }))
1688
+ ] });
1689
+ }
1690
+
1691
+ // src/components/PostList.tsx
1692
+ import { jsx as jsx12, jsxs as jsxs10 } from "react/jsx-runtime";
1693
+ var STATUS_LABEL = {
1694
+ draft: "statusDraft",
1695
+ scheduled: "statusScheduled",
1696
+ published: "statusPublished",
1697
+ archived: "statusArchived"
1698
+ };
1699
+ function PostList({ onSelect, onCreate, pageSize = 20, reloadKey }) {
1700
+ const { messages, locale } = useContentText();
1701
+ const { posts, tags, filters, updateFilters, page, setPage, hasFilters } = usePostList({
1702
+ pageSize,
1703
+ ...reloadKey !== void 0 ? { reloadKey } : {}
1704
+ });
1705
+ const searchId = useId6();
1706
+ const statusId = useId6();
1707
+ const tagId = useId6();
1708
+ return /* @__PURE__ */ jsxs10("section", { className: "adc-root adc-post-list", children: [
1709
+ /* @__PURE__ */ jsxs10("header", { className: "adc-toolbar", children: [
1710
+ /* @__PURE__ */ jsx12("h2", { className: "adc-title", children: messages.listTitle }),
1711
+ onCreate && /* @__PURE__ */ jsxs10("button", { type: "button", className: "adc-button adc-button--primary", onClick: onCreate, children: [
1712
+ /* @__PURE__ */ jsx12(Plus, { "aria-hidden": "true", className: "adc-icon" }),
1713
+ messages.newPost
1714
+ ] })
1715
+ ] }),
1716
+ /* @__PURE__ */ jsxs10("div", { className: "adc-filters", children: [
1717
+ /* @__PURE__ */ jsxs10("div", { className: "adc-field adc-field--search", children: [
1718
+ /* @__PURE__ */ jsx12("label", { htmlFor: searchId, children: messages.searchLabel }),
1719
+ /* @__PURE__ */ jsxs10("div", { className: "adc-input-icon", children: [
1720
+ /* @__PURE__ */ jsx12(Search, { "aria-hidden": "true", className: "adc-icon" }),
1721
+ /* @__PURE__ */ jsx12(
1722
+ "input",
1723
+ {
1724
+ id: searchId,
1725
+ type: "search",
1726
+ placeholder: messages.searchPlaceholder,
1727
+ value: filters.search ?? "",
1728
+ onChange: (event) => updateFilters({ ...filters, search: event.target.value || void 0 })
1729
+ }
1730
+ )
1731
+ ] })
1732
+ ] }),
1733
+ /* @__PURE__ */ jsxs10("div", { className: "adc-field", children: [
1734
+ /* @__PURE__ */ jsx12("label", { htmlFor: statusId, children: messages.filterStatus }),
1735
+ /* @__PURE__ */ jsxs10(
1736
+ "select",
1737
+ {
1738
+ id: statusId,
1739
+ value: filters.status ?? "",
1740
+ onChange: (event) => updateFilters({ ...filters, status: event.target.value || void 0 }),
1741
+ children: [
1742
+ /* @__PURE__ */ jsx12("option", { value: "", children: messages.filterAll }),
1743
+ POST_STATUSES.map((status) => /* @__PURE__ */ jsx12("option", { value: status, children: messages[STATUS_LABEL[status]] }, status))
1744
+ ]
1745
+ }
1746
+ )
1747
+ ] }),
1748
+ /* @__PURE__ */ jsxs10("div", { className: "adc-field", children: [
1749
+ /* @__PURE__ */ jsx12("label", { htmlFor: tagId, children: messages.filterTag }),
1750
+ /* @__PURE__ */ jsx12(
1751
+ "input",
1752
+ {
1753
+ id: tagId,
1754
+ list: tags && tags.length > 0 ? `${tagId}-list` : void 0,
1755
+ value: filters.tag ?? "",
1756
+ onChange: (event) => updateFilters({ ...filters, tag: event.target.value || void 0 })
1757
+ }
1758
+ ),
1759
+ tags && /* @__PURE__ */ jsx12("datalist", { id: `${tagId}-list`, children: tags.map((entry) => /* @__PURE__ */ jsx12("option", { value: entry.tag }, entry.tag)) })
1760
+ ] }),
1761
+ hasFilters && /* @__PURE__ */ jsxs10("button", { type: "button", className: "adc-button adc-button--ghost", onClick: () => updateFilters({}), children: [
1762
+ /* @__PURE__ */ jsx12(RotateCcw, { "aria-hidden": "true", className: "adc-icon" }),
1763
+ messages.clearFilters
1764
+ ] })
1765
+ ] }),
1766
+ posts.error !== void 0 && !posts.isLoading ? /* @__PURE__ */ jsxs10("div", { className: "adc-state adc-state--error", role: "alert", children: [
1767
+ messages.loadError,
1768
+ /* @__PURE__ */ jsx12("button", { type: "button", className: "adc-button", onClick: posts.reload, children: messages.retry })
1769
+ ] }) : posts.isLoading && !posts.data ? /* @__PURE__ */ jsx12("p", { className: "adc-state", role: "status", children: messages.loading }) : (posts.data?.data.length ?? 0) === 0 ? /* @__PURE__ */ jsx12("p", { className: "adc-state", children: messages.empty }) : /* @__PURE__ */ jsx12("div", { className: "adc-table-wrap", "aria-busy": posts.isLoading, children: /* @__PURE__ */ jsxs10("table", { className: "adc-table", children: [
1770
+ /* @__PURE__ */ jsx12("thead", { children: /* @__PURE__ */ jsxs10("tr", { children: [
1771
+ /* @__PURE__ */ jsx12("th", { scope: "col", children: messages.columnTitle }),
1772
+ /* @__PURE__ */ jsx12("th", { scope: "col", children: messages.columnStatus }),
1773
+ /* @__PURE__ */ jsx12("th", { scope: "col", children: messages.columnPublished }),
1774
+ /* @__PURE__ */ jsx12("th", { scope: "col", children: messages.columnUpdated })
1775
+ ] }) }),
1776
+ /* @__PURE__ */ jsx12("tbody", { children: posts.data?.data.map((post) => /* @__PURE__ */ jsxs10("tr", { children: [
1777
+ /* @__PURE__ */ jsxs10("td", { children: [
1778
+ /* @__PURE__ */ jsx12("button", { type: "button", className: "adc-row-link", onClick: () => onSelect(post), children: post.title }),
1779
+ /* @__PURE__ */ jsxs10("span", { className: "adc-muted adc-slug", children: [
1780
+ "/",
1781
+ post.slug
1782
+ ] })
1783
+ ] }),
1784
+ /* @__PURE__ */ jsx12("td", { children: /* @__PURE__ */ jsx12(StatusChip, { status: post.status }) }),
1785
+ /* @__PURE__ */ jsx12("td", { children: formatPostDate(post.publishedAt, locale, true) }),
1786
+ /* @__PURE__ */ jsx12("td", { children: formatPostDate(post.updatedAt, locale, true) })
1787
+ ] }, post.id)) })
1788
+ ] }) }),
1789
+ posts.data && /* @__PURE__ */ jsx12(Pagination, { page, totalPages: posts.data.pagination.totalPages, onPageChange: setPage })
1790
+ ] });
1791
+ }
1792
+
1793
+ // src/components/ContentWorkspace.tsx
1794
+ import { jsx as jsx13 } from "react/jsx-runtime";
1795
+ function ContentWorkspace({
1796
+ pageSize,
1797
+ newPostDefaults,
1798
+ onPostSaved,
1799
+ showFormattingToolbar,
1800
+ renderDateTimeInput
1801
+ }) {
1802
+ const [view, setView] = useState11({ kind: "list" });
1803
+ const [reloadKey, setReloadKey] = useState11(0);
1804
+ function handleSaved(post) {
1805
+ setReloadKey((value) => value + 1);
1806
+ setView({ kind: "editor", postId: post.id });
1807
+ onPostSaved?.(post);
1808
+ }
1809
+ if (view.kind === "editor") {
1810
+ return /* @__PURE__ */ jsx13(
1811
+ PostEditor,
1812
+ {
1813
+ ...view.postId ? { postId: view.postId } : {},
1814
+ ...newPostDefaults ? { defaults: newPostDefaults } : {},
1815
+ ...showFormattingToolbar === void 0 ? {} : { showFormattingToolbar },
1816
+ ...renderDateTimeInput ? { renderDateTimeInput } : {},
1817
+ onSaved: handleSaved,
1818
+ onArchived: () => {
1819
+ setReloadKey((value) => value + 1);
1820
+ setView({ kind: "list" });
1821
+ },
1822
+ onClose: () => setView({ kind: "list" })
1823
+ },
1824
+ view.postId ?? "new"
1825
+ );
1826
+ }
1827
+ return /* @__PURE__ */ jsx13(
1828
+ PostList,
1829
+ {
1830
+ reloadKey,
1831
+ ...pageSize ? { pageSize } : {},
1832
+ onSelect: (post) => setView({ kind: "editor", postId: post.id }),
1833
+ onCreate: () => setView({ kind: "editor" })
1834
+ }
1835
+ );
1836
+ }
1837
+
1838
+ // src/components/PostCard.tsx
1839
+ import { jsx as jsx14, jsxs as jsxs11 } from "react/jsx-runtime";
1840
+ function PostCard({ post, href, headingLevel = 2 }) {
1841
+ const { messages, locale, format } = useContentText();
1842
+ const renderLink = useRenderLink();
1843
+ const Heading = `h${headingLevel}`;
1844
+ return /* @__PURE__ */ jsxs11("article", { className: "adc-card", children: [
1845
+ post.coverImageUrl && /* @__PURE__ */ jsx14(
1846
+ "img",
1847
+ {
1848
+ className: "adc-card-cover",
1849
+ src: post.coverImageUrl,
1850
+ alt: post.coverImageAlt ?? "",
1851
+ loading: "lazy",
1852
+ decoding: "async"
1853
+ }
1854
+ ),
1855
+ /* @__PURE__ */ jsxs11("div", { className: "adc-card-body", children: [
1856
+ /* @__PURE__ */ jsx14(Heading, { className: "adc-card-title", children: renderLink({ href, className: "adc-card-link", children: post.title }) }),
1857
+ /* @__PURE__ */ jsxs11("p", { className: "adc-meta", children: [
1858
+ /* @__PURE__ */ jsx14("time", { dateTime: post.publishedAt, children: formatPostDate(post.publishedAt, locale) }),
1859
+ /* @__PURE__ */ jsx14("span", { "aria-hidden": "true", children: " \xB7 " }),
1860
+ format("readingTime", { minutes: post.readingTimeMinutes })
1861
+ ] }),
1862
+ post.excerpt && /* @__PURE__ */ jsx14("p", { className: "adc-card-excerpt", children: post.excerpt }),
1863
+ post.tags.length > 0 && /* @__PURE__ */ jsx14("ul", { className: "adc-tag-list", children: post.tags.map((tag) => /* @__PURE__ */ jsx14("li", { className: "adc-tag", children: tag }, tag)) }),
1864
+ /* @__PURE__ */ jsx14("span", { className: "adc-card-more", "aria-hidden": "true", children: messages.readMore })
1865
+ ] })
1866
+ ] });
1867
+ }
1868
+
1869
+ // src/components/PostListPage.tsx
1870
+ import { jsx as jsx15, jsxs as jsxs12 } from "react/jsx-runtime";
1871
+ function PostListPage({ page = 1, tag, pageSize = 10, getPostHref, getListHref, title }) {
1872
+ const api = useContentPublicApi();
1873
+ const { messages } = useContentText();
1874
+ const renderLink = useRenderLink();
1875
+ const posts = useAsyncResource(
1876
+ () => api.listPublishedPosts({ page, pageSize, ...tag ? { tag } : {} }),
1877
+ JSON.stringify({ page, pageSize, tag })
1878
+ );
1879
+ const tags = useAsyncResource(
1880
+ () => api.listTags ? api.listTags() : Promise.resolve([]),
1881
+ "public-tags"
1882
+ );
1883
+ const withTag = (target) => getListHref({ page: target, ...tag ? { tag } : {} });
1884
+ return /* @__PURE__ */ jsxs12("section", { className: "adc-root adc-public-list", children: [
1885
+ title && /* @__PURE__ */ jsx15("h1", { className: "adc-page-title", children: title }),
1886
+ (tags.data?.length ?? 0) > 0 && /* @__PURE__ */ jsxs12("nav", { className: "adc-tag-filter", "aria-label": messages.tagsLabel, children: [
1887
+ renderLink({
1888
+ href: getListHref({ page: 1 }),
1889
+ className: `adc-tag-chip${tag ? "" : " adc-tag-chip--active"}`,
1890
+ ...tag ? {} : { "aria-current": "page" },
1891
+ children: messages.allTags
1892
+ }),
1893
+ tags.data?.map(
1894
+ (entry) => renderLink({
1895
+ href: getListHref({ page: 1, tag: entry.tag }),
1896
+ className: `adc-tag-chip${entry.tag === tag ? " adc-tag-chip--active" : ""}`,
1897
+ ...entry.tag === tag ? { "aria-current": "page" } : {},
1898
+ children: `${entry.tag} (${entry.count})`
1899
+ })
1900
+ )
1901
+ ] }),
1902
+ posts.isLoading && !posts.data ? /* @__PURE__ */ jsx15("p", { className: "adc-state", role: "status", children: messages.loading }) : posts.error !== void 0 ? /* @__PURE__ */ jsxs12("div", { className: "adc-state adc-state--error", role: "alert", children: [
1903
+ messages.loadError,
1904
+ /* @__PURE__ */ jsx15("button", { type: "button", className: "adc-button", onClick: posts.reload, children: messages.retry })
1905
+ ] }) : (posts.data?.data.length ?? 0) === 0 ? /* @__PURE__ */ jsx15("p", { className: "adc-state", children: messages.postsEmpty }) : /* @__PURE__ */ jsx15("div", { className: "adc-card-grid", children: posts.data?.data.map((post) => /* @__PURE__ */ jsx15(PostCard, { post, href: getPostHref(post.slug) }, post.id)) }),
1906
+ posts.data && /* @__PURE__ */ jsx15(Pagination, { page, totalPages: posts.data.pagination.totalPages, getPageHref: withTag })
1907
+ ] });
1908
+ }
1909
+
1910
+ // src/components/PostPage.tsx
1911
+ import { useEffect as useEffect5 } from "react";
1912
+
1913
+ // src/components/ShareButtons.tsx
1914
+ import { Check, Link2, Share2 } from "lucide-react";
1915
+ import { useEffect as useEffect4, useState as useState12 } from "react";
1916
+
1917
+ // src/lib/share.ts
1918
+ var SHARE_NETWORK = {
1919
+ WHATSAPP: "whatsapp",
1920
+ FACEBOOK: "facebook",
1921
+ X: "x",
1922
+ LINKEDIN: "linkedin"
1923
+ };
1924
+ var SHARE_NETWORKS = Object.values(SHARE_NETWORK);
1925
+ function buildShareLinks(params) {
1926
+ const url = encodeURIComponent(params.url);
1927
+ const text = encodeURIComponent(params.title);
1928
+ return [
1929
+ {
1930
+ network: SHARE_NETWORK.WHATSAPP,
1931
+ href: `https://wa.me/?text=${encodeURIComponent(`${params.title} ${params.url}`)}`
1932
+ },
1933
+ { network: SHARE_NETWORK.FACEBOOK, href: `https://www.facebook.com/sharer/sharer.php?u=${url}` },
1934
+ { network: SHARE_NETWORK.X, href: `https://x.com/intent/post?url=${url}&text=${text}` },
1935
+ { network: SHARE_NETWORK.LINKEDIN, href: `https://www.linkedin.com/sharing/share-offsite/?url=${url}` }
1936
+ ];
1937
+ }
1938
+
1939
+ // src/components/ShareButtons.tsx
1940
+ import { jsx as jsx16, jsxs as jsxs13 } from "react/jsx-runtime";
1941
+ var NETWORK_LABEL = {
1942
+ [SHARE_NETWORK.WHATSAPP]: "shareWhatsApp",
1943
+ [SHARE_NETWORK.FACEBOOK]: "shareFacebook",
1944
+ [SHARE_NETWORK.X]: "shareX",
1945
+ [SHARE_NETWORK.LINKEDIN]: "shareLinkedIn"
1946
+ };
1947
+ var COPIED_FEEDBACK_MS = 2e3;
1948
+ function ShareButtons({ url, title, networks }) {
1949
+ const { messages, format } = useContentText();
1950
+ const [isCopied, setIsCopied] = useState12(false);
1951
+ const links = buildShareLinks({ url, title }).filter((link) => !networks || networks.includes(link.network));
1952
+ const [capabilities, setCapabilities] = useState12({ canShareNatively: false, canCopy: false });
1953
+ useEffect4(() => {
1954
+ setCapabilities({
1955
+ canShareNatively: typeof navigator.share === "function",
1956
+ canCopy: Boolean(navigator.clipboard)
1957
+ });
1958
+ }, []);
1959
+ const { canShareNatively, canCopy } = capabilities;
1960
+ async function handleCopy() {
1961
+ await navigator.clipboard.writeText(url);
1962
+ setIsCopied(true);
1963
+ window.setTimeout(() => setIsCopied(false), COPIED_FEEDBACK_MS);
1964
+ }
1965
+ return /* @__PURE__ */ jsxs13("div", { className: "adc-share", role: "group", "aria-label": messages.shareLabel, children: [
1966
+ /* @__PURE__ */ jsx16("span", { className: "adc-label", children: messages.shareLabel }),
1967
+ canShareNatively && /* @__PURE__ */ jsxs13(
1968
+ "button",
1969
+ {
1970
+ type: "button",
1971
+ className: "adc-button",
1972
+ onClick: () => void navigator.share({ url, title }).catch(() => void 0),
1973
+ children: [
1974
+ /* @__PURE__ */ jsx16(Share2, { "aria-hidden": "true", className: "adc-icon" }),
1975
+ messages.shareNative
1976
+ ]
1977
+ }
1978
+ ),
1979
+ links.map((link) => /* @__PURE__ */ jsx16(
1980
+ "a",
1981
+ {
1982
+ className: `adc-button adc-share-link adc-share-link--${link.network}`,
1983
+ href: link.href,
1984
+ target: "_blank",
1985
+ rel: "noopener noreferrer",
1986
+ "aria-label": format("shareOn", { network: messages[NETWORK_LABEL[link.network]] }),
1987
+ children: messages[NETWORK_LABEL[link.network]]
1988
+ },
1989
+ link.network
1990
+ )),
1991
+ canCopy && /* @__PURE__ */ jsxs13("button", { type: "button", className: "adc-button", onClick: () => void handleCopy().catch(() => void 0), children: [
1992
+ isCopied ? /* @__PURE__ */ jsx16(Check, { "aria-hidden": "true", className: "adc-icon" }) : /* @__PURE__ */ jsx16(Link2, { "aria-hidden": "true", className: "adc-icon" }),
1993
+ /* @__PURE__ */ jsx16("span", { "aria-live": "polite", children: isCopied ? messages.linkCopied : messages.copyLink })
1994
+ ] })
1995
+ ] });
1996
+ }
1997
+
1998
+ // src/components/PostPage.tsx
1999
+ import { Fragment, jsx as jsx17, jsxs as jsxs14 } from "react/jsx-runtime";
2000
+ function PostPage({ slug, shareUrl, shareNetworks, getTagHref, onLoaded, renderNotFound }) {
2001
+ const api = useContentPublicApi();
2002
+ const { messages, locale, format } = useContentText();
2003
+ const renderLink = useRenderLink();
2004
+ const resource = useAsyncResource(() => api.getPublishedPost(slug), slug);
2005
+ const post = resource.data;
2006
+ useEffect5(() => {
2007
+ if (post) onLoaded?.(post);
2008
+ }, [post, onLoaded]);
2009
+ if (resource.isLoading && !post) {
2010
+ return /* @__PURE__ */ jsx17("p", { className: "adc-root adc-state", role: "status", children: messages.loading });
2011
+ }
2012
+ if (!post) {
2013
+ return /* @__PURE__ */ jsx17(Fragment, { children: renderNotFound ? renderNotFound() : /* @__PURE__ */ jsx17("p", { className: "adc-root adc-state", children: messages.notFound }) });
2014
+ }
2015
+ const url = shareUrl ?? (typeof window !== "undefined" ? window.location.href : "");
2016
+ return /* @__PURE__ */ jsxs14("article", { className: "adc-root adc-post", children: [
2017
+ /* @__PURE__ */ jsxs14("header", { className: "adc-post-header", children: [
2018
+ /* @__PURE__ */ jsx17("h1", { className: "adc-page-title", children: post.title }),
2019
+ /* @__PURE__ */ jsxs14("p", { className: "adc-meta", children: [
2020
+ /* @__PURE__ */ jsx17("time", { dateTime: post.publishedAt, children: formatPostDate(post.publishedAt, locale) }),
2021
+ /* @__PURE__ */ jsx17("span", { "aria-hidden": "true", children: " \xB7 " }),
2022
+ format("readingTime", { minutes: post.readingTimeMinutes }),
2023
+ post.authorName && /* @__PURE__ */ jsxs14(Fragment, { children: [
2024
+ /* @__PURE__ */ jsx17("span", { "aria-hidden": "true", children: " \xB7 " }),
2025
+ format("byAuthor", { author: post.authorName })
2026
+ ] })
2027
+ ] }),
2028
+ post.tags.length > 0 && /* @__PURE__ */ jsx17("ul", { className: "adc-tag-list", children: post.tags.map((tag) => /* @__PURE__ */ jsx17("li", { className: "adc-tag", children: getTagHref ? renderLink({ href: getTagHref(tag), children: tag }) : tag }, tag)) })
2029
+ ] }),
2030
+ post.coverImageUrl && /* @__PURE__ */ jsx17("img", { className: "adc-post-cover", src: post.coverImageUrl, alt: post.coverImageAlt ?? "", decoding: "async" }),
2031
+ /* @__PURE__ */ jsx17(MarkdownContent, { markdown: post.body, headingLevelOffset: 1 }),
2032
+ url && shareNetworks?.length !== 0 && /* @__PURE__ */ jsx17(ShareButtons, { url, title: post.title, ...shareNetworks ? { networks: shareNetworks } : {} })
2033
+ ] });
2034
+ }
2035
+
2036
+ // src/lib/seo.ts
2037
+ import { buildExcerpt } from "@adatechnology/content-contracts";
2038
+ function buildPostMeta(post, params) {
2039
+ const baseTitle = post.seoTitle ?? post.title;
2040
+ const title = params.siteName ? `${baseTitle} | ${params.siteName}` : baseTitle;
2041
+ const description = post.seoDescription ?? post.excerpt ?? buildExcerpt(post.body, 160);
2042
+ const url = post.canonicalUrl ?? params.url;
2043
+ return {
2044
+ title,
2045
+ description,
2046
+ canonicalUrl: url,
2047
+ openGraph: {
2048
+ type: "article",
2049
+ title: baseTitle,
2050
+ description,
2051
+ url,
2052
+ ...post.coverImageUrl ? { image: post.coverImageUrl } : {},
2053
+ ...post.coverImageAlt ? { imageAlt: post.coverImageAlt } : {},
2054
+ publishedTime: post.publishedAt,
2055
+ modifiedTime: post.updatedAt,
2056
+ tags: post.tags
2057
+ }
2058
+ };
2059
+ }
2060
+ export {
2061
+ COVER_MAX_BYTES,
2062
+ COVER_MIME_TYPES,
2063
+ ContentProvider,
2064
+ ContentWorkspace,
2065
+ DEFAULT_CONTENT_LOCALE,
2066
+ DRAFT_ERROR,
2067
+ EMOJI_BY_CATEGORY,
2068
+ EMOJI_CATEGORIES,
2069
+ EMPTY_POST_DRAFT,
2070
+ EmojiPicker,
2071
+ FilePicker,
2072
+ MarkdownContent,
2073
+ MarkdownEditor,
2074
+ Pagination,
2075
+ PostCard,
2076
+ PostEditor,
2077
+ PostList,
2078
+ PostListPage,
2079
+ PostPage,
2080
+ SHARE_NETWORK,
2081
+ SHARE_NETWORKS,
2082
+ ShareButtons,
2083
+ StatusChip,
2084
+ TagsInput,
2085
+ buildPageItems,
2086
+ buildPostMeta,
2087
+ buildShareLinks,
2088
+ deriveSlug,
2089
+ draftFromPost,
2090
+ draftToInput,
2091
+ formatPostDate,
2092
+ fromDateTimeLocalValue,
2093
+ insertImage,
2094
+ insertLink,
2095
+ insertText,
2096
+ interpolate,
2097
+ isDraftDirty,
2098
+ resolveContentMessages,
2099
+ searchEmoji,
2100
+ splitTagInput,
2101
+ toDateTimeLocalValue,
2102
+ toggleLinePrefix,
2103
+ toggleWrap,
2104
+ useAsyncResource,
2105
+ useContentAdminApi,
2106
+ useContentPublicApi,
2107
+ useContentText,
2108
+ usePostEditor,
2109
+ usePostList,
2110
+ useRenderLink,
2111
+ useUnsavedChangesGuard,
2112
+ validateDraft
2113
+ };
2114
+ //# sourceMappingURL=index.js.map