@jsb188/mday-web 1.1.8 → 1.1.11

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.
@@ -0,0 +1,963 @@
1
+ import i18n from '@jsb188/app/i18n/index.ts';
2
+ import type { ServerErrorObj } from '@jsb188/app/types/app.d.ts';
3
+ import { buildSingleText, cn } from '@jsb188/app/utils/string.ts';
4
+ import {
5
+ useChildOrganizations,
6
+ useOrganizationMembers,
7
+ } from '@jsb188/graphql/hooks/use-organization-qry';
8
+ import type {
9
+ DocAccessBaseObj,
10
+ DocAccessGranteeTypeEnum,
11
+ DocAccessGrantObj,
12
+ DocAccessObj,
13
+ DocAccessScopeEnum,
14
+ DocGrantPermissionEnum,
15
+ DocPermissionEnum,
16
+ } from '@jsb188/mday/types/docAccess.d.ts';
17
+ import {
18
+ buildDocAccessSavePayload,
19
+ getDocAccessGrantMaps,
20
+ getDocAccessScope,
21
+ isDocAccessOverruledRole,
22
+ maxDocPermission,
23
+ minDocPermission,
24
+ normalizeDocAccess,
25
+ } from '@jsb188/mday/utils/docAccess.ts';
26
+ import { checkACL } from '@jsb188/mday/utils/organization.ts';
27
+ import { ListItemWithDropdown } from '@jsb188/react-web/modules/List';
28
+ import {
29
+ PopOverOptionsButton,
30
+ TooltipButton,
31
+ } from '@jsb188/react-web/modules/PopOver';
32
+ import { COMMON_ICON_NAMES } from '@jsb188/react-web/svgs/Icon';
33
+ import { Button, SimpleLabel } from '@jsb188/react-web/ui/Button';
34
+ import Markdown from '@jsb188/react-web/ui/Markdown';
35
+ import type {
36
+ ModalScrollableOption,
37
+ ModalScrollableOptionRow,
38
+ } from '@jsb188/react-web/ui/ModalUI';
39
+ import {
40
+ ModalErrorMessage,
41
+ ModalScrollableOptions,
42
+ ModalToolbar,
43
+ } from '@jsb188/react-web/ui/ModalUI';
44
+ import { copyTextToClipboard } from '@jsb188/react-web/hooks/use-dom';
45
+ import type { ModalHandlerProps } from '@jsb188/react/states';
46
+ import { memo, useEffect, useMemo, useRef, useState } from 'react';
47
+ import {
48
+ getOrgOperationIconName,
49
+ getOrgRoleLabelPreset,
50
+ } from '../utils/org-web.ts';
51
+
52
+ /**
53
+ * Types
54
+ */
55
+
56
+ // Which document type's i18n namespace holds the "access_*" copy; also
57
+ // namespaces the pop over ids so they match the pre-extraction Sheet ids
58
+ export type DocAccessTextNamespace = 'sheet' | 'agentDoc';
59
+
60
+ interface AccessPickListItem {
61
+ id: string;
62
+ text: string;
63
+ role?: string | null;
64
+ operation?: string | null;
65
+ // Member cannot write org data ("general_write"): the team policy caps
66
+ // them at view, so only an explicit grant can give them edit
67
+ writeCapped?: boolean;
68
+ }
69
+
70
+ interface AccessPickRowTarget {
71
+ granteeType: DocAccessGranteeTypeEnum;
72
+ id: string;
73
+ }
74
+
75
+ type PermissionMap = Record<string, DocGrantPermissionEnum>;
76
+
77
+ interface DocAccessCustomPermissionCounts {
78
+ membersCount: number;
79
+ orgsCount: number;
80
+ }
81
+
82
+ type DocAccessSettingsProps = ModalHandlerProps & {
83
+ organizationId: string;
84
+ access?: DocAccessBaseObj | null;
85
+ canEditAccess?: boolean;
86
+ // The grants list and its loading state, injected by the document-type
87
+ // wrapper so this module stays free of entity-specific GraphQL hooks
88
+ accessGrants?: DocAccessGrantObj[] | null;
89
+ grantsLoading?: boolean;
90
+ // Save handler + mutation state, injected by the document-type wrapper
91
+ onSave: (access: DocAccessObj) => void;
92
+ saving?: boolean;
93
+ error?: ServerErrorObj | null;
94
+ resetErrors: () => void;
95
+ // Absolute shareable link for the document (copied by the footer button)
96
+ shareLink: string;
97
+ textNamespace: DocAccessTextNamespace;
98
+ // Hide the "Anyone with link" scope for document types whose server
99
+ // refuses a PUBLIC policy (agent docs have no signed-out route)
100
+ hidePublicOption?: boolean;
101
+ };
102
+
103
+ /*
104
+ * Translate one access-settings text under the document-type i18n namespace
105
+ * ("sheet.access_*" or "agentDoc.access_*"), so copy that names the document
106
+ * type stays correct without concatenating translations.
107
+ */
108
+ function tDocAccess(
109
+ textNamespace: DocAccessTextNamespace,
110
+ key: string,
111
+ options?: Record<string, any>,
112
+ ) {
113
+ return i18n.t(`${textNamespace}.${key}`, options);
114
+ }
115
+
116
+ /*
117
+ * Return whether one mapped picker row can be rendered.
118
+ */
119
+ function isAccessPickListItem(
120
+ item: AccessPickListItem | null,
121
+ ): item is AccessPickListItem {
122
+ return !!item;
123
+ }
124
+
125
+ /*
126
+ * Build a display name for one organization member picker row.
127
+ */
128
+ function getOrganizationMemberPickListItem(
129
+ memberRel: any,
130
+ ): AccessPickListItem | null {
131
+ const account = memberRel?.account;
132
+ if (!account?.id || account.deleted) {
133
+ return null;
134
+ }
135
+
136
+ return {
137
+ id: String(account.id),
138
+ text:
139
+ buildSingleText(
140
+ [account.profile?.firstName, account.profile?.lastName],
141
+ ' ',
142
+ ) ||
143
+ account.displayName ||
144
+ '',
145
+ role: memberRel?.role || null,
146
+ writeCapped: checkACL(memberRel, 'general_write') === false,
147
+ };
148
+ }
149
+
150
+ /*
151
+ * Build a display name for one child organization picker row.
152
+ */
153
+ function getChildOrganizationPickListItem(
154
+ childRel: any,
155
+ ): AccessPickListItem | null {
156
+ const childOrganization = childRel?.organization;
157
+ if (!childOrganization?.id) {
158
+ return null;
159
+ }
160
+
161
+ return {
162
+ id: String(childOrganization.id),
163
+ text: childOrganization.name || '',
164
+ operation: childOrganization.operation || null,
165
+ };
166
+ }
167
+
168
+ /*
169
+ * Sort access picker items alphabetically by display text while keeping
170
+ * duplicate names in a stable ID order.
171
+ */
172
+ function sortAccessPickListItemsByText(items: AccessPickListItem[]) {
173
+ return [...items].sort((a, b) => {
174
+ const textCompare = a.text.localeCompare(b.text, undefined, {
175
+ sensitivity: 'base',
176
+ });
177
+
178
+ return textCompare || a.id.localeCompare(b.id);
179
+ });
180
+ }
181
+
182
+ /*
183
+ * Build one sticky title row for a document access options section.
184
+ */
185
+ function getDocAccessScrollableHeaderOption(
186
+ text: string,
187
+ className = '',
188
+ ): ModalScrollableOptionRow {
189
+ return {
190
+ items: [
191
+ {
192
+ text,
193
+ className: 'f px_4 ft_medium',
194
+ },
195
+ ],
196
+ stickyHeader: true,
197
+ className,
198
+ };
199
+ }
200
+
201
+ /*
202
+ * Build one disabled empty-state row for an empty picker section.
203
+ */
204
+ function getDocAccessScrollableEmptyOption(
205
+ text: string,
206
+ ): ModalScrollableOptionRow {
207
+ return {
208
+ items: [
209
+ {
210
+ text,
211
+ className: 'f p_4 cl_md',
212
+ },
213
+ ],
214
+ disabled: true,
215
+ };
216
+ }
217
+
218
+ /*
219
+ * Return the toolbar icon for the current document access scope.
220
+ */
221
+ function getDocAccessToolbarIconName(scope: DocAccessScopeEnum) {
222
+ return scope === 'PUBLIC' ? 'earth-1' : 'earth-lock';
223
+ }
224
+
225
+ /*
226
+ * Return the list icon for one general access scope option.
227
+ */
228
+ function getDocAccessScopeIconName(scope: DocAccessScopeEnum) {
229
+ switch (scope) {
230
+ case 'PUBLIC':
231
+ return COMMON_ICON_NAMES.public;
232
+ case 'NETWORK':
233
+ return COMMON_ICON_NAMES.share_to_orgs;
234
+ case 'RESTRICTED':
235
+ default:
236
+ return COMMON_ICON_NAMES.invite_only;
237
+ }
238
+ }
239
+
240
+ /*
241
+ * Return the description explaining the chosen team permission.
242
+ */
243
+ function getDocAccessTeamDescription(
244
+ textNamespace: DocAccessTextNamespace,
245
+ permission: DocPermissionEnum,
246
+ ) {
247
+ switch (permission) {
248
+ case 'EDIT':
249
+ return tDocAccess(textNamespace, 'access_team_edit_msg');
250
+ case 'VIEW':
251
+ return tDocAccess(textNamespace, 'access_team_view_msg');
252
+ case 'NONE':
253
+ default:
254
+ return tDocAccess(textNamespace, 'access_team_none_msg');
255
+ }
256
+ }
257
+
258
+ /*
259
+ * Return the description explaining the chosen general access scope (the
260
+ * network scope's description reflects its view/edit permission).
261
+ */
262
+ function getDocAccessScopeDescription(
263
+ textNamespace: DocAccessTextNamespace,
264
+ scope: DocAccessScopeEnum,
265
+ networkPermission: DocGrantPermissionEnum,
266
+ ) {
267
+ switch (scope) {
268
+ case 'PUBLIC':
269
+ return tDocAccess(textNamespace, 'access_anyone_with_link_msg');
270
+ case 'NETWORK':
271
+ return tDocAccess(
272
+ textNamespace,
273
+ networkPermission === 'EDIT'
274
+ ? 'access_network_edit_msg'
275
+ : 'access_network_view_msg',
276
+ );
277
+ case 'RESTRICTED':
278
+ default:
279
+ return tDocAccess(textNamespace, 'access_only_invites_msg');
280
+ }
281
+ }
282
+
283
+ /*
284
+ * Count explicit grantee permissions that still change what a row gets from
285
+ * the currently selected general access rules, after applying the public
286
+ * link's view floor.
287
+ */
288
+ function getDocAccessCustomPermissionCount(
289
+ items: AccessPickListItem[],
290
+ permissions: PermissionMap,
291
+ publicFloorPermission: DocPermissionEnum,
292
+ getGeneralPermission: (item: AccessPickListItem) => DocPermissionEnum,
293
+ ) {
294
+ return items.reduce((count, item) => {
295
+ const permission = permissions[item.id];
296
+ if (!permission || isDocAccessOverruledRole(item.role)) {
297
+ return count;
298
+ }
299
+
300
+ const generalEffectivePermission = maxDocPermission(
301
+ getGeneralPermission(item),
302
+ publicFloorPermission,
303
+ );
304
+ const grantEffectivePermission = maxDocPermission(
305
+ permission,
306
+ publicFloorPermission,
307
+ );
308
+
309
+ return generalEffectivePermission === grantEffectivePermission
310
+ ? count
311
+ : count + 1;
312
+ }, 0);
313
+ }
314
+
315
+ /*
316
+ * Return the localized markdown summary for custom member and network
317
+ * organization permissions, omitting whichever count is empty.
318
+ */
319
+ function getDocAccessCustomPermissionsMessage(
320
+ textNamespace: DocAccessTextNamespace,
321
+ counts: DocAccessCustomPermissionCounts,
322
+ ) {
323
+ const { membersCount, orgsCount } = counts;
324
+
325
+ if (membersCount > 0 && orgsCount > 0) {
326
+ if (membersCount === 1 && orgsCount === 1) {
327
+ return tDocAccess(
328
+ textNamespace,
329
+ 'access_custom_member_permission_org_permission_msg',
330
+ { membersCount, orgsCount },
331
+ );
332
+ }
333
+
334
+ if (membersCount === 1) {
335
+ return tDocAccess(
336
+ textNamespace,
337
+ 'access_custom_member_permission_org_permissions_msg',
338
+ { membersCount, orgsCount },
339
+ );
340
+ }
341
+
342
+ if (orgsCount === 1) {
343
+ return tDocAccess(
344
+ textNamespace,
345
+ 'access_custom_member_permissions_org_permission_msg',
346
+ { membersCount, orgsCount },
347
+ );
348
+ }
349
+
350
+ return tDocAccess(
351
+ textNamespace,
352
+ 'access_custom_member_permissions_org_permissions_msg',
353
+ { membersCount, orgsCount },
354
+ );
355
+ }
356
+
357
+ if (membersCount > 0) {
358
+ return tDocAccess(
359
+ textNamespace,
360
+ membersCount === 1
361
+ ? 'access_custom_member_permission_msg'
362
+ : 'access_custom_member_permissions_msg',
363
+ { membersCount },
364
+ );
365
+ }
366
+
367
+ if (orgsCount > 0) {
368
+ return tDocAccess(
369
+ textNamespace,
370
+ orgsCount === 1
371
+ ? 'access_custom_org_permission_msg'
372
+ : 'access_custom_org_permissions_msg',
373
+ { orgsCount },
374
+ );
375
+ }
376
+
377
+ return '';
378
+ }
379
+
380
+ // How long the "Link copied!" confirmation stays before resetting
381
+ const DOC_ACCESS_COPIED_RESET_MS = 3000;
382
+
383
+ /*
384
+ * Copy-link button for the document access settings footer. It copies the
385
+ * shareable link and shows a "Link copied!" confirmation (check icon,
386
+ * primary color) for 3 seconds; clicking again restarts the timer. It owns
387
+ * its own copied state so the timer never re-renders the whole modal.
388
+ */
389
+ const DocAccessCopyLinkButton = memo(
390
+ (p: { link: string; textNamespace: DocAccessTextNamespace }) => {
391
+ const { link, textNamespace } = p;
392
+ const [copied, setCopied] = useState(false);
393
+ const resetTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
394
+
395
+ useEffect(() => {
396
+ // Cancel any pending reset when the button unmounts
397
+ return () => {
398
+ if (resetTimeoutRef.current) {
399
+ clearTimeout(resetTimeoutRef.current);
400
+ }
401
+ };
402
+ }, []);
403
+
404
+ /*
405
+ * Copy the link, show the confirmation, and (re)start the reset timer.
406
+ */
407
+ const copyLink = () => {
408
+ copyTextToClipboard(link);
409
+ setCopied(true);
410
+
411
+ if (resetTimeoutRef.current) {
412
+ clearTimeout(resetTimeoutRef.current);
413
+ }
414
+
415
+ resetTimeoutRef.current = setTimeout(() => {
416
+ resetTimeoutRef.current = null;
417
+ setCopied(false);
418
+ }, DOC_ACCESS_COPIED_RESET_MS);
419
+ };
420
+
421
+ return (
422
+ <Button
423
+ className={cn('f gap_5', copied && 'cl_primary')}
424
+ preset="outline_subtle"
425
+ leftIconName={copied ? 'check' : COMMON_ICON_NAMES.hyperlink}
426
+ text={tDocAccess(
427
+ textNamespace,
428
+ copied ? 'access_link_copied' : 'access_copy_link',
429
+ )}
430
+ onClick={copyLink}
431
+ />
432
+ );
433
+ },
434
+ );
435
+
436
+ DocAccessCopyLinkButton.displayName = 'DocAccessCopyLinkButton';
437
+
438
+ /*
439
+ * View and edit one document's access settings modal screen. The "General
440
+ * access" section holds the team permission row and the general access
441
+ * scope row (network organizations, invite-only, or public link); the
442
+ * picker below lists every team member and network org with its own
443
+ * permission dropdown. A row's dropdown stores an explicit grant whenever
444
+ * the chosen permission differs from what the general rules already give
445
+ * that grantee: grants are overrides, so they can raise or lower one
446
+ * grantee's access (including "No access"). Grants persist across scope
447
+ * switches, so flipping scopes never drops the overrides. Editing requires
448
+ * the document type's edit ACL, resolved by the opener into the
449
+ * "canEditAccess" prop; other viewers get a read-only view. The wrapper
450
+ * injects the grants list, the save handler, and the shareable link, so
451
+ * this module stays document-type agnostic.
452
+ */
453
+ export default function DocAccessSettings(p: DocAccessSettingsProps) {
454
+ const {
455
+ accessGrants,
456
+ canEditAccess,
457
+ closeModalScreen,
458
+ error,
459
+ grantsLoading,
460
+ hidePublicOption,
461
+ onSave,
462
+ organizationId,
463
+ resetErrors,
464
+ saving,
465
+ shareLink,
466
+ textNamespace,
467
+ } = p;
468
+ const initialAccess = normalizeDocAccess(p.access);
469
+ const [scope, setScope] = useState<DocAccessScopeEnum>(
470
+ getDocAccessScope(initialAccess),
471
+ );
472
+ const [teamPermission, setTeamPermission] = useState<DocPermissionEnum>(
473
+ initialAccess.team,
474
+ );
475
+ const [networkPermission, setNetworkPermission] =
476
+ useState<DocGrantPermissionEnum>(
477
+ initialAccess.network === 'EDIT' ? 'EDIT' : 'VIEW',
478
+ );
479
+
480
+ // The grants list loads separately from the document fragment (owner-org
481
+ // only); edits overlay it so an untouched screen saves the same grants back
482
+ const loadedGrantMaps = useMemo(
483
+ () => getDocAccessGrantMaps(accessGrants),
484
+ [accessGrants],
485
+ );
486
+ const [dirtyAccountPermissions, setDirtyAccountPermissions] =
487
+ useState<PermissionMap | null>(null);
488
+ const [dirtyOrganizationPermissions, setDirtyOrganizationPermissions] =
489
+ useState<PermissionMap | null>(null);
490
+ const accountPermissions =
491
+ dirtyAccountPermissions ?? loadedGrantMaps.accountPermissions;
492
+ const organizationPermissions =
493
+ dirtyOrganizationPermissions ?? loadedGrantMaps.organizationPermissions;
494
+
495
+ // Guests are listed too: the team policy applies to them (capped at view
496
+ // for read-only members), and an explicit grant is the only way to raise
497
+ // or block one of them
498
+ const { organizationMembers } = useOrganizationMembers(organizationId, true);
499
+ const { childOrganizations } = useChildOrganizations({ organizationId });
500
+
501
+ const breadcrumbs = useMemo(
502
+ () => [
503
+ {
504
+ text: tDocAccess(textNamespace, 'access_settings'),
505
+ iconName: getDocAccessToolbarIconName(scope),
506
+ },
507
+ ],
508
+ [scope, textNamespace],
509
+ );
510
+
511
+ /*
512
+ * Build the account rows for the team members picker list.
513
+ */
514
+ const memberItems = useMemo<AccessPickListItem[]>(() => {
515
+ if (!Array.isArray(organizationMembers)) {
516
+ return [];
517
+ }
518
+
519
+ return sortAccessPickListItemsByText(
520
+ organizationMembers
521
+ .map(getOrganizationMemberPickListItem)
522
+ .filter(isAccessPickListItem),
523
+ );
524
+ }, [organizationMembers]);
525
+
526
+ /*
527
+ * Build the child organization rows for the network organizations picker list.
528
+ */
529
+ const childOrgItems = useMemo<AccessPickListItem[]>(() => {
530
+ if (!Array.isArray(childOrganizations)) {
531
+ return [];
532
+ }
533
+
534
+ return childOrganizations
535
+ .map(getChildOrganizationPickListItem)
536
+ .filter(isAccessPickListItem);
537
+ }, [childOrganizations]);
538
+
539
+ // Full permission options, shared by the team dropdown and grantee rows
540
+ const permissionOptions = useMemo(
541
+ () => [
542
+ {
543
+ text: tDocAccess(textNamespace, 'access_can_edit'),
544
+ iconName: COMMON_ICON_NAMES.access_edit,
545
+ value: 'EDIT',
546
+ },
547
+ {
548
+ text: tDocAccess(textNamespace, 'access_can_view'),
549
+ iconName: COMMON_ICON_NAMES.access_view,
550
+ value: 'VIEW',
551
+ },
552
+ {
553
+ text: tDocAccess(textNamespace, 'access_no_access'),
554
+ iconName: COMMON_ICON_NAMES.access_none,
555
+ textClassName: 'op_30',
556
+ value: 'NONE',
557
+ },
558
+ ],
559
+ [textNamespace],
560
+ );
561
+
562
+ const scopeOptions = useMemo(
563
+ () => [
564
+ {
565
+ text: tDocAccess(textNamespace, 'access_only_invites'),
566
+ value: 'RESTRICTED',
567
+ iconName: getDocAccessScopeIconName('RESTRICTED'),
568
+ },
569
+ {
570
+ text: tDocAccess(textNamespace, 'access_network_orgs'),
571
+ value: 'NETWORK',
572
+ iconName: getDocAccessScopeIconName('NETWORK'),
573
+ },
574
+ ...(hidePublicOption
575
+ ? []
576
+ : [
577
+ {
578
+ text: tDocAccess(textNamespace, 'access_anyone_with_link'),
579
+ value: 'PUBLIC',
580
+ iconName: getDocAccessScopeIconName('PUBLIC'),
581
+ },
582
+ ]),
583
+ ],
584
+ [textNamespace, hidePublicOption],
585
+ );
586
+
587
+ const grantPermissionOptions = useMemo(
588
+ () => [
589
+ {
590
+ text: tDocAccess(textNamespace, 'access_can_edit'),
591
+ iconName: COMMON_ICON_NAMES.access_edit,
592
+ value: 'EDIT',
593
+ },
594
+ {
595
+ text: tDocAccess(textNamespace, 'access_can_view'),
596
+ iconName: COMMON_ICON_NAMES.access_view,
597
+ value: 'VIEW',
598
+ },
599
+ ],
600
+ [textNamespace],
601
+ );
602
+
603
+ // What the public link gives everyone regardless of overrides: a grant
604
+ // can never drop a grantee below it, since the link works signed out
605
+ const publicFloorPermission: DocPermissionEnum =
606
+ scope === 'PUBLIC' ? 'VIEW' : 'NONE';
607
+
608
+ /*
609
+ * Return the permission a team member gets from the general access rules
610
+ * (the "Team" permission; members who cannot write org data cap at view).
611
+ * Admins and owners always keep full edit access.
612
+ */
613
+ const getMemberGeneralPermission = (
614
+ item: AccessPickListItem,
615
+ ): DocPermissionEnum => {
616
+ if (isDocAccessOverruledRole(item.role)) {
617
+ return 'EDIT';
618
+ }
619
+
620
+ return item.writeCapped
621
+ ? minDocPermission(teamPermission, 'VIEW')
622
+ : teamPermission;
623
+ };
624
+
625
+ /*
626
+ * Return the permission a network organization gets from the general
627
+ * access rules (the network permission).
628
+ */
629
+ const getOrgGeneralPermission = (): DocPermissionEnum => {
630
+ return scope === 'NETWORK' ? networkPermission : 'NONE';
631
+ };
632
+
633
+ /*
634
+ * Return one grantee's effective permission: the explicit grant override
635
+ * when one exists, the general-access rule otherwise, never below the
636
+ * public link floor.
637
+ */
638
+ const getGranteeEffectivePermission = (
639
+ target: AccessPickRowTarget,
640
+ generalPermission: DocPermissionEnum,
641
+ ): DocPermissionEnum => {
642
+ const permissions =
643
+ target.granteeType === 'ACCOUNT'
644
+ ? accountPermissions
645
+ : organizationPermissions;
646
+
647
+ return maxDocPermission(
648
+ permissions[target.id] ?? generalPermission,
649
+ publicFloorPermission,
650
+ );
651
+ };
652
+
653
+ /*
654
+ * Set one grantee's permission from its row dropdown. Grants are
655
+ * overrides: choosing any permission that differs from the general-access
656
+ * rule stores an explicit grant (raising or lowering access, including
657
+ * "No access"); choosing the rule's own permission clears the override.
658
+ */
659
+ const setGranteePermission = (
660
+ target: AccessPickRowTarget,
661
+ generalPermission: DocPermissionEnum,
662
+ permission: DocPermissionEnum,
663
+ ) => {
664
+ const isAccount = target.granteeType === 'ACCOUNT';
665
+ const permissions = isAccount
666
+ ? accountPermissions
667
+ : organizationPermissions;
668
+ const setDirtyPermissions = isAccount
669
+ ? setDirtyAccountPermissions
670
+ : setDirtyOrganizationPermissions;
671
+ const nextPermissions = { ...permissions };
672
+
673
+ if (permission !== generalPermission) {
674
+ nextPermissions[target.id] = permission;
675
+ } else {
676
+ delete nextPermissions[target.id];
677
+ }
678
+
679
+ setDirtyPermissions(nextPermissions);
680
+ };
681
+
682
+ /*
683
+ * Save the chosen access settings through the wrapper's save handler.
684
+ * Saving stays disabled until the current grants load so an early save
685
+ * can never wipe grants that were not shown.
686
+ */
687
+ const saveAccessSettings = () => {
688
+ if (!canEditAccess || saving || grantsLoading) {
689
+ return;
690
+ }
691
+
692
+ const access = buildDocAccessSavePayload({
693
+ scope,
694
+ teamPermission,
695
+ networkPermission,
696
+ accountPermissions,
697
+ organizationPermissions,
698
+ });
699
+
700
+ onSave(access);
701
+ };
702
+
703
+ const optionsDisabled = !canEditAccess || grantsLoading;
704
+ const customPermissionCounts: DocAccessCustomPermissionCounts = {
705
+ membersCount: getDocAccessCustomPermissionCount(
706
+ memberItems,
707
+ accountPermissions,
708
+ publicFloorPermission,
709
+ getMemberGeneralPermission,
710
+ ),
711
+ orgsCount: getDocAccessCustomPermissionCount(
712
+ childOrgItems,
713
+ organizationPermissions,
714
+ publicFloorPermission,
715
+ () => getOrgGeneralPermission(),
716
+ ),
717
+ };
718
+ const customPermissionsMessage = grantsLoading
719
+ ? ''
720
+ : getDocAccessCustomPermissionsMessage(
721
+ textNamespace,
722
+ customPermissionCounts,
723
+ );
724
+
725
+ // Whether any team member or network org has access (through the general
726
+ // access rules or a grant override); when nobody has access, no picker
727
+ // row is faded
728
+ const anyGranteeSelected =
729
+ memberItems.some(
730
+ (item) =>
731
+ getGranteeEffectivePermission(
732
+ { granteeType: 'ACCOUNT', id: item.id },
733
+ getMemberGeneralPermission(item),
734
+ ) !== 'NONE',
735
+ ) ||
736
+ childOrgItems.some(
737
+ (item) =>
738
+ getGranteeEffectivePermission(
739
+ { granteeType: 'ORGANIZATION', id: item.id },
740
+ getOrgGeneralPermission(),
741
+ ) !== 'NONE',
742
+ );
743
+
744
+ /*
745
+ * Build one grantee picker row: a leading avatar (team members) or
746
+ * operation icon (network organizations), the grantee name, and a
747
+ * permission dropdown that reflects the grantee's effective access (the
748
+ * explicit grant override when one exists, the general access rule
749
+ * otherwise). Admins and owners always have full access, so their rows
750
+ * show the role label instead of a dropdown. Rows without effective
751
+ * access fade out, but only once at least one grantee has access.
752
+ */
753
+ const buildGranteePickerRow = (
754
+ target: AccessPickRowTarget,
755
+ name: string,
756
+ generalPermission: DocPermissionEnum,
757
+ leading: Pick<ModalScrollableOption, 'avatarDisplayName' | 'iconName'>,
758
+ role?: string | null,
759
+ ): ModalScrollableOptionRow => {
760
+ const effective = getGranteeEffectivePermission(target, generalPermission);
761
+ const isOverruledRole = isDocAccessOverruledRole(role);
762
+ const faded = anyGranteeSelected && effective === 'NONE';
763
+
764
+ return {
765
+ items: [
766
+ {
767
+ text: name,
768
+ className: cn('f min_w_0', faded && 'op_30'),
769
+ avatarDisplayName: leading.avatarDisplayName,
770
+ iconName: leading.iconName,
771
+ },
772
+ ],
773
+ RightComponent: isOverruledRole ? (
774
+ <TooltipButton
775
+ as="span"
776
+ position="top"
777
+ tooltipClassName="a_c"
778
+ message={tDocAccess(textNamespace, 'access_admin_owner_msg')}
779
+ >
780
+ <SimpleLabel
781
+ className="cs_default"
782
+ preset={getOrgRoleLabelPreset(role)}
783
+ text={i18n.t(`org.role.${role}`)}
784
+ />
785
+ </TooltipButton>
786
+ ) : (
787
+ <PopOverOptionsButton
788
+ name={`${textNamespace}_access_grantee_${target.granteeType}_${target.id}`}
789
+ className="ft_xs py_4 bg_darker_2_hv r_sm pl_8 pr_6"
790
+ position="bottom_right"
791
+ zClassName="z8"
792
+ disabled={optionsDisabled}
793
+ value={effective}
794
+ options={permissionOptions}
795
+ onChange={(value) =>
796
+ setGranteePermission(
797
+ target,
798
+ generalPermission,
799
+ value as DocPermissionEnum,
800
+ )
801
+ }
802
+ />
803
+ ),
804
+ };
805
+ };
806
+
807
+ // Two picker lists (team members, network organizations), each under its
808
+ // own sticky header; every grantee row carries its own permission dropdown
809
+ const pickerRows: ModalScrollableOptionRow[] = [
810
+ getDocAccessScrollableHeaderOption(
811
+ tDocAccess(textNamespace, 'access_team_members'),
812
+ ),
813
+ ...(memberItems.length
814
+ ? memberItems.map((item) =>
815
+ buildGranteePickerRow(
816
+ { granteeType: 'ACCOUNT', id: item.id },
817
+ item.text,
818
+ getMemberGeneralPermission(item),
819
+ { avatarDisplayName: item.text },
820
+ item.role,
821
+ ),
822
+ )
823
+ : [
824
+ getDocAccessScrollableEmptyOption(
825
+ tDocAccess(textNamespace, 'access_no_team_members_found'),
826
+ ),
827
+ ]),
828
+ getDocAccessScrollableHeaderOption(
829
+ tDocAccess(textNamespace, 'access_network_orgs'),
830
+ ),
831
+ ...(childOrgItems.length
832
+ ? childOrgItems.map((item) =>
833
+ buildGranteePickerRow(
834
+ { granteeType: 'ORGANIZATION', id: item.id },
835
+ item.text,
836
+ getOrgGeneralPermission(),
837
+ { iconName: getOrgOperationIconName(item.operation) },
838
+ ),
839
+ )
840
+ : [
841
+ getDocAccessScrollableEmptyOption(
842
+ tDocAccess(textNamespace, 'access_no_network_orgs_found'),
843
+ ),
844
+ ]),
845
+ ];
846
+
847
+ return (
848
+ <>
849
+ <ModalToolbar
850
+ // hideSeparator
851
+ breadcrumbs={breadcrumbs}
852
+ paddingClassName="px_20"
853
+ onCloseModal={closeModalScreen}
854
+ />
855
+
856
+ <div className="w_f no_shrink pt_10 pb_15 px_20">
857
+ {error && (
858
+ <div className="mb_df">
859
+ <ModalErrorMessage error={error} resetErrors={resetErrors} />
860
+ </div>
861
+ )}
862
+
863
+ <p className="ft_tn cl_md unsel px_4 ft_medium">
864
+ {tDocAccess(textNamespace, 'access_general_title')}
865
+ </p>
866
+
867
+ <div className="mt_5">
868
+ <ListItemWithDropdown
869
+ className="r_sm pl_5 pr_20 ft_sm"
870
+ iconName={COMMON_ICON_NAMES.team}
871
+ text={tDocAccess(textNamespace, 'access_level_team')}
872
+ description={getDocAccessTeamDescription(
873
+ textNamespace,
874
+ teamPermission,
875
+ )}
876
+ disabled={optionsDisabled}
877
+ rightItemOptions={{
878
+ name: `${textNamespace}_access_team`,
879
+ className: 'ft_xs',
880
+ value: teamPermission,
881
+ options: permissionOptions,
882
+ onChange: (value) =>
883
+ setTeamPermission(value as DocPermissionEnum),
884
+ }}
885
+ />
886
+
887
+ <ListItemWithDropdown
888
+ className="r_sm pl_5 pr_20 ft_sm"
889
+ iconName={getDocAccessScopeIconName(scope)}
890
+ description={getDocAccessScopeDescription(
891
+ textNamespace,
892
+ scope,
893
+ networkPermission,
894
+ )}
895
+ disabled={optionsDisabled}
896
+ titleOptions={{
897
+ name: `${textNamespace}_access_scope`,
898
+ value: scope,
899
+ options: scopeOptions,
900
+ onChange: (value) => setScope(value as DocAccessScopeEnum),
901
+ }}
902
+ rightItemOptions={
903
+ scope === 'NETWORK'
904
+ ? {
905
+ name: `${textNamespace}_access_network`,
906
+ className: 'ft_xs',
907
+ value: networkPermission,
908
+ options: grantPermissionOptions,
909
+ onChange: (value) =>
910
+ setNetworkPermission(value as DocGrantPermissionEnum),
911
+ }
912
+ : undefined
913
+ }
914
+ RightItemComponent={
915
+ scope === 'PUBLIC' ? (
916
+ <span className="ft_xs cl_md">
917
+ {tDocAccess(textNamespace, 'access_can_view')}
918
+ </span>
919
+ ) : undefined
920
+ }
921
+ />
922
+
923
+ {customPermissionsMessage && (
924
+ <Markdown
925
+ as="div"
926
+ preset="content_description"
927
+ className="mt_8 bd_1 bd_lt p_8 r_sm ft_xs cl_md"
928
+ >
929
+ {customPermissionsMessage}
930
+ </Markdown>
931
+ )}
932
+ </div>
933
+ </div>
934
+
935
+ <ModalScrollableOptions
936
+ smallerItems
937
+ className="bd_t_1 bd_lt"
938
+ size="xs"
939
+ disabled={optionsDisabled}
940
+ sizingClassNames={['f min_w_0']}
941
+ options={pickerRows}
942
+ onSelect={() => {}}
943
+ />
944
+
945
+ {canEditAccess && (
946
+ <div className="w_f no_shrink bd_t_1 bd_lt pt_15 pb_15 px_df h_item gap_10">
947
+ <DocAccessCopyLinkButton
948
+ link={shareLink}
949
+ textNamespace={textNamespace}
950
+ />
951
+
952
+ <Button
953
+ preset="bg_primary"
954
+ className="w_130 no_shrink"
955
+ text={i18n.t('form.save')}
956
+ disabled={saving || grantsLoading}
957
+ onClick={saveAccessSettings}
958
+ />
959
+ </div>
960
+ )}
961
+ </>
962
+ );
963
+ }