Skip to content

armgit / kaneo

Public Imported from GitHub
0

⚡ Project management that doesn't become the project. Boards, Gantt charts, and GitHub integration. Self-host it or use Kaneo Cloud.

fix(mobile): address the second review round

Tinbd59b877038b
diff --git a/apps/mobile/src/app/(app)/project/[projectId]/settings.tsx b/apps/mobile/src/app/(app)/project/[projectId]/settings.tsx
index bc55c6503..33a1bfda7 100644
--- a/apps/mobile/src/app/(app)/project/[projectId]/settings.tsx
+++ b/apps/mobile/src/app/(app)/project/[projectId]/settings.tsx
@@ -18,7 +18,6 @@ import { ConfirmDialog, OptionSheet, Sheet } from "@/components/sheet";
import { Txt } from "@/components/text";
import {
Button,
- Chip,
Group,
GroupRow,
IconButton,
@@ -27,6 +26,9 @@ import {
TextField,
Touch,
} from "@/components/ui";
+import { CustomFieldForm } from "@/features/project/custom-field-form";
+import type { CreateFieldBody } from "@/features/project/field-form";
+import { useFieldTypes } from "@/features/project/use-field-types";
import { userMessage } from "@/lib/api/client";
import { api } from "@/lib/api/endpoints";
import type { Column, CustomFieldDefinition } from "@/lib/api/types";
@@ -34,18 +36,6 @@ import { useWorkspaces } from "@/lib/hooks";
import { qk, useAction } from "@/lib/query";
import { useColors } from "@/theme";
-function useFieldTypes() {
- const { t } = useTranslation(["mobile"]);
- return [
- { value: "text", label: t("mobile:projectSettings.text") },
- { value: "number", label: t("mobile:projectSettings.number") },
- { value: "date", label: t("mobile:projectSettings.date") },
- { value: "boolean", label: t("mobile:projectSettings.checkbox") },
- { value: "dropdown", label: t("mobile:projectSettings.dropdown") },
- { value: "multiselect", label: t("mobile:projectSettings.multiSelect") },
- ];
-}
-
export default function ProjectSettingsScreen() {
const { t } = useTranslation(["mobile"]);
const fieldTypes = useFieldTypes();
@@ -424,6 +414,7 @@ export default function ProjectSettingsScreen() {
}
/>
<AddFieldSheet
+ busy={busy}
visible={addingField}
onClose={() => setAddingField(false)}
onAdd={(body) =>
@@ -621,15 +612,12 @@ function AddFieldSheet({
visible,
onClose,
onAdd,
+ busy,
}: {
visible: boolean;
onClose: () => void;
- onAdd: (body: {
- name: string;
- type: string;
- required: boolean;
- options?: string[];
- }) => void;
+ onAdd: (body: CreateFieldBody) => Promise<unknown | undefined>;
+ busy: boolean;
}) {
const { t } = useTranslation(["mobile"]);
return (
@@ -638,91 +626,7 @@ function AddFieldSheet({
onClose={onClose}
title={t("mobile:projectSettings.newCustomField")}
>
- <AddFieldForm onClose={onClose} onAdd={onAdd} />
+ <CustomFieldForm onClose={onClose} onAdd={onAdd} busy={busy} />
</Sheet>
);
}
-
-function AddFieldForm({
- onClose,
- onAdd,
-}: {
- onClose: () => void;
- onAdd: (body: {
- name: string;
- type: string;
- required: boolean;
- options?: string[];
- }) => void;
-}) {
- const { t } = useTranslation(["mobile"]);
- const fieldTypes = useFieldTypes();
- const [name, setName] = useState("");
- const [type, setType] = useState("text");
- const [optionsText, setOptionsText] = useState("");
- const [required, setRequired] = useState(false);
- const needsOptions = type === "dropdown" || type === "multiselect";
- const options = optionsText
- .split(",")
- .map((o) => o.trim())
- .filter(Boolean);
-
- return (
- <View style={{ paddingHorizontal: 20, paddingBottom: 12, gap: 16 }}>
- <TextField
- label={t("mobile:projectSettings.name")}
- value={name}
- onChangeText={setName}
- placeholder={t("mobile:projectSettings.platform")}
- autoFocus
- />
- <View style={{ gap: 8 }}>
- <Txt variant="meta" weight="medium" tone="body">
- {t("mobile:projectSettings.type")}
- </Txt>
- <View style={{ flexDirection: "row", flexWrap: "wrap", gap: 6 }}>
- {fieldTypes.map((fieldType) => (
- <Chip
- key={fieldType.value}
- label={fieldType.label}
- selected={type === fieldType.value}
- onPress={() => setType(fieldType.value)}
- />
- ))}
- </View>
- </View>
- {needsOptions ? (
- <TextField
- label={t("mobile:projectSettings.options")}
- aside={t("mobile:projectSettings.separateWithCommas")}
- value={optionsText}
- onChangeText={setOptionsText}
- placeholder={t("mobile:projectSettings.androidIOSWeb")}
- />
- ) : null}
- <View
- style={{
- flexDirection: "row",
- alignItems: "center",
- justifyContent: "space-between",
- }}
- >
- <Txt variant="bodySm">{t("mobile:projectSettings.required")}</Txt>
- <Switch value={required} onChange={setRequired} />
- </View>
- <Button
- label={t("mobile:projectSettings.addField")}
- disabled={!name.trim() || (needsOptions && options.length === 0)}
- onPress={() => {
- onAdd({
- name: name.trim(),
- type,
- required,
- options: needsOptions ? options : undefined,
- });
- onClose();
- }}
- />
- </View>
- );
-}
diff --git a/apps/mobile/src/app/(app)/search.tsx b/apps/mobile/src/app/(app)/search.tsx
index cabb5994d..1aac7e006 100644
--- a/apps/mobile/src/app/(app)/search.tsx
+++ b/apps/mobile/src/app/(app)/search.tsx
@@ -40,12 +40,16 @@ export default function SearchScreen() {
queryFn: () => api.search(query, workspaceId, kind),
enabled: query.length > 0,
});
- const results = search.data?.results ?? [];
const groups: { title: string; type: string }[] = [
{ title: t("mobile:search.kinds.tasks"), type: "task" },
{ title: t("mobile:search.kinds.comments"), type: "comment" },
+ { title: t("mobile:search.kinds.activity"), type: "activity" },
{ title: t("mobile:search.kinds.projects"), type: "project" },
];
+ // Only count result types the screen has a group for, so the empty state still shows.
+ const results = (search.data?.results ?? []).filter((r) =>
+ groups.some((g) => g.type === r.type),
+ );
const commentMeta = (r: SearchResult) => {
const when = relativeLong(r.createdAt);
@@ -63,7 +67,7 @@ export default function SearchScreen() {
pathname: "/board/[projectId]",
params: { projectId: r.id, workspaceId: r.workspaceId ?? workspaceId },
});
- // Comment hits only carry the task's ticket key, so resolve it to a task id.
+ // Comment and activity hits only carry the task's ticket key, so resolve it to a task id.
if (r.projectSlug && r.taskNumber) {
try {
const task = await api.taskByTicketId(
@@ -180,6 +184,7 @@ export default function SearchScreen() {
groups.map((g) => {
const items = results.filter((r) => r.type === g.type);
if (!items.length) return null;
+ const isNote = g.type === "comment" || g.type === "activity";
return (
<View key={g.type} style={{ paddingTop: 16 }}>
<View
@@ -203,8 +208,7 @@ export default function SearchScreen() {
onPress={() => open(r)}
style={{
flexDirection: "row",
- alignItems:
- g.type === "comment" ? "flex-start" : "center",
+ alignItems: isNote ? "flex-start" : "center",
gap: 12,
minHeight: 56,
paddingHorizontal: inset,
@@ -213,13 +217,13 @@ export default function SearchScreen() {
>
<View
style={{
- width: g.type === "comment" ? 24 : 16,
- paddingTop: g.type === "comment" ? 2 : 0,
+ width: isNote ? 24 : 16,
+ paddingTop: isNote ? 2 : 0,
}}
>
{g.type === "task" ? (
<StatusIcon status={r.status ?? "to-do"} />
- ) : g.type === "comment" ? (
+ ) : isNote ? (
<Avatar name={r.userName ?? "?"} size={24} />
) : (
<ProjectIcon color={c.ink2} />
@@ -227,14 +231,12 @@ export default function SearchScreen() {
</View>
<View style={{ flex: 1, gap: 3 }}>
<Txt
- variant={g.type === "comment" ? "bodySm" : "body"}
- tone={g.type === "comment" ? "body" : "ink"}
- numberOfLines={g.type === "comment" ? 3 : 1}
+ variant={isNote ? "bodySm" : "body"}
+ tone={isNote ? "body" : "ink"}
+ numberOfLines={isNote ? 3 : 1}
style={{ lineHeight: 20 }}
>
- {g.type === "comment"
- ? toPlainText(r.content ?? r.title)
- : r.title}
+ {isNote ? toPlainText(r.content ?? r.title) : r.title}
</Txt>
<View style={{ flexDirection: "row", gap: 8 }}>
{r.taskNumber ? (
@@ -248,7 +250,7 @@ export default function SearchScreen() {
numberOfLines={1}
style={{ flex: 1 }}
>
- {g.type === "comment"
+ {isNote
? commentMeta(r)
: (r.projectName ??
(g.type === "project"
diff --git a/apps/mobile/src/app/(app)/task/new.tsx b/apps/mobile/src/app/(app)/task/new.tsx
index feb3b0585..d692c3968 100644
--- a/apps/mobile/src/app/(app)/task/new.tsx
+++ b/apps/mobile/src/app/(app)/task/new.tsx
@@ -22,7 +22,13 @@ import { DatePickerSheet, TextInputSheet } from "@/components/pickers";
import { BackButton, Screen } from "@/components/screen";
import { MultiSelectSheet, OptionSheet, Sheet } from "@/components/sheet";
import { Txt } from "@/components/text";
+import { useToast } from "@/components/toast";
import { Checkbox, LabelDot, Switch, Touch } from "@/components/ui";
+import {
+ customFieldsPayload,
+ draftFieldValues,
+ hasMissingRequired,
+} from "@/features/task/new-task-fields";
import { api } from "@/lib/api/endpoints";
import type { CustomFieldDefinition, Json } from "@/lib/api/types";
import { formatDate, toApiDate, toIsoDay, type Day } from "@/lib/format";
@@ -70,6 +76,7 @@ export default function NewTaskScreen() {
const c = useColors();
const session = useRequiredSession();
const { run, busy } = useAction();
+ const toast = useToast();
const [projectId, setProjectId] = useState(params.projectId);
const workspaceId = params.workspaceId;
@@ -96,7 +103,7 @@ export default function NewTaskScreen() {
const [start, setStart] = useState<Day | null>(null);
const [due, setDue] = useState<Day | null>(null);
const [labelIds, setLabelIds] = useState<string[]>([]);
- const [fieldValues, setFieldValues] = useState<Record<string, string>>({});
+ const [fieldEdits, setFieldEdits] = useState<Record<string, string>>({});
const [picker, setPicker] = useState<Picker>(null);
const [fieldEditing, setFieldEditing] =
useState<CustomFieldDefinition | null>(null);
@@ -118,14 +125,16 @@ export default function NewTaskScreen() {
const sortedFields = [...(fields.data ?? [])].sort(
(a, b) => (a.position ?? 0) - (b.position ?? 0),
);
- const missingRequired = sortedFields.some(
- (f) => f.required && !fieldValues[f.id]?.trim(),
- );
- const canCreate = !!title.trim() && !busy && !missingRequired;
+ const fieldValues = draftFieldValues(sortedFields, fieldEdits);
+ const canCreate =
+ !!title.trim() && !busy && !hasMissingRequired(sortedFields, fieldValues);
+ const setFieldValue = (id: string, value: string) =>
+ setFieldEdits({ ...fieldEdits, [id]: value });
const create = async () => {
- const task = await run(async () => {
- const created = await api.createTask(projectId, {
+ // Once the task exists the form must not create it again, so failed follow-ups only warn.
+ const result = await run(async () => {
+ const task = await api.createTask(projectId, {
title: title.trim(),
description,
startDate: start ? toApiDate(start) : null,
@@ -133,22 +142,32 @@ export default function NewTaskScreen() {
priority,
status: effectiveStatus,
userId: assignee,
- customFields: Object.entries(fieldValues)
- .filter(([, v]) => v.trim())
- .map(([fieldId, value]) => ({ fieldId, value })),
+ customFields: customFieldsPayload(sortedFields, fieldValues),
});
- await Promise.all(
- labelIds.map((id) => api.attachLabel(id, created.id).catch(() => null)),
- );
- if (params.parentTaskId)
- await api.createRelation(params.parentTaskId, created.id, "subtask");
- return created;
+ const [labelResults, linked] = await Promise.all([
+ Promise.allSettled(labelIds.map((id) => api.attachLabel(id, task.id))),
+ params.parentTaskId
+ ? api.createRelation(params.parentTaskId, task.id, "subtask").then(
+ () => true,
+ () => false,
+ )
+ : true,
+ ]);
+ const labelsFailed = labelResults.some((r) => r.status === "rejected");
+ return { task, labelsFailed, linked };
});
- if (task)
- router.replace({
- pathname: "/task/[taskId]",
- params: { taskId: task.id },
- });
+ if (!result) return;
+ const { task, labelsFailed, linked } = result;
+ router.replace({ pathname: "/task/[taskId]", params: { taskId: task.id } });
+ if (!linked)
+ toast.show(
+ labelsFailed
+ ? t("mobile:taskNew.labelsAndParentFailed")
+ : t("mobile:taskNew.parentFailed"),
+ "error",
+ );
+ else if (labelsFailed)
+ toast.show(t("mobile:taskNew.labelsFailed"), "error");
};
const row = (
@@ -459,9 +478,7 @@ export default function NewTaskScreen() {
<View style={{ flex: 1 }} />
<Switch
value={value === "true"}
- onChange={(v) =>
- setFieldValues({ ...fieldValues, [f.id]: String(v) })
- }
+ onChange={(v) => setFieldValue(f.id, String(v))}
/>
</View>
);
@@ -505,7 +522,7 @@ export default function NewTaskScreen() {
onSelect={(id) => {
setProjectId(id);
setStatus(null);
- setFieldValues({});
+ setFieldEdits({});
}}
/>
<OptionSheet
@@ -631,10 +648,7 @@ export default function NewTaskScreen() {
value={fieldEditing ? fieldValues[fieldEditing.id] : null}
onPick={(day) =>
fieldEditing &&
- setFieldValues({
- ...fieldValues,
- [fieldEditing.id]: day ? toIsoDay(day) : "",
- })
+ setFieldValue(fieldEditing.id, day ? toIsoDay(day) : "")
}
/>
<OptionSheet
@@ -649,10 +663,7 @@ export default function NewTaskScreen() {
label: o,
})),
]}
- onSelect={(v) =>
- fieldEditing &&
- setFieldValues({ ...fieldValues, [fieldEditing.id]: v })
- }
+ onSelect={(v) => fieldEditing && setFieldValue(fieldEditing.id, v)}
/>
<MultiSelectSheet
visible={fieldEditing?.type === "multiselect"}
@@ -663,11 +674,7 @@ export default function NewTaskScreen() {
fieldEditing ? options(fieldValues[fieldEditing.id] ?? null) : []
}
onSave={(values) =>
- fieldEditing &&
- setFieldValues({
- ...fieldValues,
- [fieldEditing.id]: JSON.stringify(values),
- })
+ fieldEditing && setFieldValue(fieldEditing.id, JSON.stringify(values))
}
/>
<TextInputSheet
@@ -682,10 +689,7 @@ export default function NewTaskScreen() {
fieldEditing?.type === "number" ? "decimal-pad" : "default"
}
validate={() => true}
- onSubmit={(v) =>
- fieldEditing &&
- setFieldValues({ ...fieldValues, [fieldEditing.id]: v })
- }
+ onSubmit={(v) => fieldEditing && setFieldValue(fieldEditing.id, v)}
/>
</Screen>
);
diff --git a/apps/mobile/src/app/(app)/workspace/[workspaceId]/labels.tsx b/apps/mobile/src/app/(app)/workspace/[workspaceId]/labels.tsx
index 10795e99c..d7e23498a 100644
--- a/apps/mobile/src/app/(app)/workspace/[workspaceId]/labels.tsx
+++ b/apps/mobile/src/app/(app)/workspace/[workspaceId]/labels.tsx
@@ -28,13 +28,18 @@ import type { Label } from "@/lib/api/types";
import { useWorkspaceLabels } from "@/lib/hooks";
import { useAction } from "@/lib/query";
import { LABEL_COLORS, labelColor } from "@/lib/style";
+import { useWorkspaceCapabilities } from "@/lib/use-workspace-capabilities";
import { inset, useColors } from "@/theme";
export default function LabelsScreen() {
const { workspaceId } = useLocalSearchParams<{ workspaceId: string }>();
const { t } = useTranslation(["mobile"]);
const c = useColors();
- const { run } = useAction();
+ const { run, busy } = useAction();
+ const capabilities = useWorkspaceCapabilities(workspaceId);
+ const canCreate = capabilities.data?.createLabels === true;
+ const canUpdate = capabilities.data?.updateLabels === true;
+ const canDelete = capabilities.data?.deleteLabels === true;
const labels = useWorkspaceLabels(workspaceId);
const [editing, setEditing] = useState<Label | "new" | null>(null);
const [menu, setMenu] = useState<Label | null>(null);
@@ -45,20 +50,25 @@ export default function LabelsScreen() {
<Screen>
<Scroll
bottomPadding={40}
- refreshing={labels.isRefetching}
- onRefresh={() => void labels.refetch()}
+ refreshing={labels.isRefetching || capabilities.isRefetching}
+ onRefresh={() => {
+ void labels.refetch();
+ void capabilities.refetch();
+ }}
>
<PageHeader
title={t("mobile:labels.title")}
description={t("mobile:labels.description")}
action={
- <Button
- label={t("mobile:labels.new")}
- size="sm"
- icon={<Plus size={14} color={c.onPrimary} />}
- onPress={() => setEditing("new")}
- style={{ height: 36 }}
- />
+ canCreate ? (
+ <Button
+ label={t("mobile:labels.new")}
+ size="sm"
+ icon={<Plus size={14} color={c.onPrimary} />}
+ onPress={() => setEditing("new")}
+ style={{ height: 36 }}
+ />
+ ) : undefined
}
/>
<View style={{ paddingHorizontal: inset }}>
@@ -82,21 +92,23 @@ export default function LabelsScreen() {
<GroupRow
key={l.id}
last={i === list.length - 1}
- onPress={() => setEditing(l)}
+ onPress={canUpdate ? () => setEditing(l) : undefined}
>
<LabelDot color={l.color} size={10} />
<Txt variant="body" style={{ flex: 1 }}>
{l.name}
</Txt>
- <Touch
- onPress={() => setMenu(l)}
- hitSlop={10}
- accessibilityLabel={t("mobile:labels.actions", {
- name: l.name,
- })}
- >
- <Ellipsis size={16} color={c.placeholder} />
- </Touch>
+ {canUpdate || canDelete ? (
+ <Touch
+ onPress={() => setMenu(l)}
+ hitSlop={10}
+ accessibilityLabel={t("mobile:labels.actions", {
+ name: l.name,
+ })}
+ >
+ <Ellipsis size={16} color={c.placeholder} />
+ </Touch>
+ ) : null}
</GroupRow>
))}
</Group>
@@ -105,37 +117,46 @@ export default function LabelsScreen() {
</Scroll>
<LabelSheet
- label={editing}
+ label={(editing === "new" ? canCreate : canUpdate) ? editing : null}
+ busy={busy}
onClose={() => setEditing(null)}
- onSave={(name, color) =>
- run(() =>
- editing && editing !== "new"
+ onSave={async (name, color) => {
+ if (!editing || !(editing === "new" ? canCreate : canUpdate)) return;
+ return run(() =>
+ editing !== "new"
? api.updateLabel(editing.id, { name, color })
: api.createLabel({ name, color, workspaceId }),
- )
- }
+ );
+ }}
/>
<OptionSheet
- visible={!!menu}
+ visible={!!menu && (canUpdate || canDelete)}
onClose={() => setMenu(null)}
title={menu?.name ?? t("mobile:labels.fallbackTitle")}
options={[
- { value: "edit", label: t("mobile:labels.edit") },
- {
- value: "delete",
- label: t("mobile:labels.delete"),
- tone: "danger" as const,
- },
+ ...(canUpdate
+ ? [{ value: "edit", label: t("mobile:labels.edit") }]
+ : []),
+ ...(canDelete
+ ? [
+ {
+ value: "delete",
+ label: t("mobile:labels.delete"),
+ tone: "danger" as const,
+ },
+ ]
+ : []),
]}
onSelect={(v) => (v === "edit" ? setEditing(menu) : setDeleting(menu))}
/>
<ConfirmDialog
- visible={!!deleting}
+ visible={!!deleting && canDelete}
title={t("mobile:labels.deleteTitle", { name: deleting?.name })}
message={t("mobile:labels.deleteMessage")}
confirmLabel={t("mobile:common.delete")}
onClose={() => setDeleting(null)}
onConfirm={() =>
+ canDelete &&
deleting &&
run(() => api.deleteLabel(deleting.id), {
success: t("mobile:labels.toast.deleted"),
@@ -148,12 +169,14 @@ export default function LabelsScreen() {
function LabelSheet({
label,
+ busy,
onClose,
onSave,
}: {
label: Label | "new" | null;
+ busy: boolean;
onClose: () => void;
- onSave: (name: string, color: string) => void;
+ onSave: (name: string, color: string) => Promise<Label | undefined>;
}) {
const { t } = useTranslation(["mobile"]);
return (
@@ -165,9 +188,10 @@ function LabelSheet({
{label ? (
<LabelForm
initial={label === "new" ? null : label}
- onSave={(name, color) => {
- onSave(name, color);
- onClose();
+ busy={busy}
+ onSave={async (name, color) => {
+ const saved = await onSave(name, color);
+ if (saved !== undefined) onClose();
}}
/>
) : null}
@@ -177,10 +201,12 @@ function LabelSheet({
function LabelForm({
initial,
+ busy,
onSave,
}: {
initial: Label | null;
- onSave: (name: string, color: string) => void;
+ busy: boolean;
+ onSave: (name: string, color: string) => Promise<void>;
}) {
const { t } = useTranslation(["mobile"]);
const c = useColors();
@@ -235,7 +261,8 @@ function LabelForm({
</View>
<Button
label={t("mobile:common.save")}
- disabled={!name.trim()}
+ loading={busy}
+ disabled={busy || !name.trim()}
onPress={() => onSave(name.trim(), color)}
/>
</View>
diff --git a/apps/mobile/src/app/(app)/workspace/[workspaceId]/members.tsx b/apps/mobile/src/app/(app)/workspace/[workspaceId]/members.tsx
index 1e2e8aae3..f2481ee4a 100644
--- a/apps/mobile/src/app/(app)/workspace/[workspaceId]/members.tsx
+++ b/apps/mobile/src/app/(app)/workspace/[workspaceId]/members.tsx
@@ -34,13 +34,11 @@ import { formatDate } from "@/lib/format";
import { useWorkspaces } from "@/lib/hooks";
import { qk, useAction } from "@/lib/query";
import { useRequiredSession } from "@/lib/session";
+import { hasRole, ROLE_HINTS, roleLabel, WORKSPACE_ROLES } from "@/lib/style";
import {
- canManageWorkspace,
- hasRole,
- ROLE_HINTS,
- roleLabel,
- WORKSPACE_ROLES,
-} from "@/lib/style";
+ useCanCancelInvitations,
+ useWorkspaceCapabilities,
+} from "@/lib/use-workspace-capabilities";
import { useColors } from "@/theme";
export default function MembersScreen() {
@@ -59,10 +57,13 @@ export default function MembersScreen() {
});
const workspaces = useWorkspaces();
const workspace = workspaces.data?.find((w) => w.id === workspaceId);
- const canManage = canManageWorkspace(
- workspace?.role ??
- org.data?.members?.find((m) => m.userId === session.userId)?.role,
- );
+ const capabilities = useWorkspaceCapabilities(workspaceId);
+ const cancellation = useCanCancelInvitations(workspaceId);
+ const canInvite = capabilities.data?.inviteUsers === true;
+ const canUpdateMembers = capabilities.data?.updateMembers === true;
+ const canRemoveMembers = capabilities.data?.removeMembers === true;
+ const canCancelInvitations = cancellation.data === true;
+ const canManageInvitations = canInvite || canCancelInvitations;
const roles = [
...WORKSPACE_ROLES,
...(rolesQuery.data ?? [])
@@ -92,8 +93,16 @@ export default function MembersScreen() {
<Screen>
<Scroll
bottomPadding={40}
- refreshing={org.isRefetching}
- onRefresh={() => void org.refetch()}
+ refreshing={
+ org.isRefetching ||
+ capabilities.isRefetching ||
+ cancellation.isRefetching
+ }
+ onRefresh={() => {
+ void org.refetch();
+ void capabilities.refetch();
+ void cancellation.refetch();
+ }}
>
<PageHeader
title={t("mobile:members.title")}
@@ -105,7 +114,7 @@ export default function MembersScreen() {
t("mobile:members.thisWorkspace"),
})}
action={
- canManage ? (
+ canInvite ? (
<Button
label={t("mobile:members.invite")}
size="sm"
@@ -135,7 +144,11 @@ export default function MembersScreen() {
<GroupRow
key={inv.id}
last={i === pending.length - 1}
- onPress={canManage ? () => setInviteMenu(inv) : undefined}
+ onPress={
+ canManageInvitations
+ ? () => setInviteMenu(inv)
+ : undefined
+ }
>
<View
style={{
@@ -164,7 +177,7 @@ export default function MembersScreen() {
: roleLabel(inv.role ?? "member")}
</Txt>
</View>
- {canManage ? (
+ {canManageInvitations ? (
<Txt variant="meta" weight="medium" tone="muted">
{t("mobile:members.pending.manage")}
</Txt>
@@ -179,7 +192,9 @@ export default function MembersScreen() {
{members.map((m, i) => {
const isSelf = m.userId === session.userId;
const editable =
- canManage && !hasRole(m.role, "owner") && !isSelf;
+ (canUpdateMembers || canRemoveMembers) &&
+ !hasRole(m.role, "owner") &&
+ !isSelf;
return (
<GroupRow
key={m.id}
@@ -234,32 +249,43 @@ export default function MembersScreen() {
</Scroll>
<InviteSheet
- visible={inviting}
+ visible={inviting && canInvite}
onClose={() => setInviting(false)}
workspaceId={workspaceId}
workspaceName={workspace?.name ?? ""}
roles={roles}
/>
<OptionSheet
- visible={!!memberMenu}
+ visible={!!memberMenu && (canUpdateMembers || canRemoveMembers)}
onClose={() => setMemberMenu(null)}
title={
memberMenu?.user?.name ?? t("mobile:members.memberMenu.fallbackTitle")
}
options={[
- { value: "role", label: t("mobile:members.memberMenu.changeRole") },
- {
- value: "remove",
- label: t("mobile:members.memberMenu.remove"),
- tone: "danger" as const,
- },
+ ...(canUpdateMembers
+ ? [
+ {
+ value: "role",
+ label: t("mobile:members.memberMenu.changeRole"),
+ },
+ ]
+ : []),
+ ...(canRemoveMembers
+ ? [
+ {
+ value: "remove",
+ label: t("mobile:members.memberMenu.remove"),
+ tone: "danger" as const,
+ },
+ ]
+ : []),
]}
onSelect={(v) =>
v === "role" ? setRolePicker(memberMenu) : setRemoving(memberMenu)
}
/>
<OptionSheet
- visible={!!rolePicker}
+ visible={!!rolePicker && canUpdateMembers}
onClose={() => setRolePicker(null)}
title={t("mobile:members.rolePicker.title")}
selected={rolePicker?.role}
@@ -269,6 +295,7 @@ export default function MembersScreen() {
hint: ROLE_HINTS[r] ?? null,
}))}
onSelect={(role) =>
+ canUpdateMembers &&
rolePicker &&
run(() => api.updateMemberRole(workspaceId, rolePicker.id, role), {
success: t("mobile:members.toast.roleUpdated"),
@@ -276,7 +303,7 @@ export default function MembersScreen() {
}
/>
<ConfirmDialog
- visible={!!removing}
+ visible={!!removing && canRemoveMembers}
title={t("mobile:members.remove.title")}
message={t("mobile:members.remove.message", {
name: removing?.user?.name ?? t("mobile:members.remove.they"),
@@ -285,6 +312,7 @@ export default function MembersScreen() {
confirmLabel={t("mobile:members.remove.confirm")}
onClose={() => setRemoving(null)}
onConfirm={() =>
+ canRemoveMembers &&
removing &&
run(
() =>
@@ -297,23 +325,34 @@ export default function MembersScreen() {
}
/>
<OptionSheet
- visible={!!inviteMenu}
+ visible={!!inviteMenu && canManageInvitations}
onClose={() => setInviteMenu(null)}
title={
inviteMenu?.email ?? t("mobile:members.inviteMenu.fallbackTitle")
}
options={[
- { value: "resend", label: t("mobile:members.inviteMenu.resend") },
- {
- value: "cancel",
- label: t("mobile:members.inviteMenu.cancel"),
- tone: "danger" as const,
- },
+ ...(canInvite
+ ? [
+ {
+ value: "resend",
+ label: t("mobile:members.inviteMenu.resend"),
+ },
+ ]
+ : []),
+ ...(canCancelInvitations
+ ? [
+ {
+ value: "cancel",
+ label: t("mobile:members.inviteMenu.cancel"),
+ tone: "danger" as const,
+ },
+ ]
+ : []),
]}
onSelect={(v) => {
const inv = inviteMenu;
if (!inv) return;
- if (v === "resend")
+ if (v === "resend" && canInvite)
void run(
() =>
api.inviteMember({
@@ -326,7 +365,7 @@ export default function MembersScreen() {
success: t("mobile:members.toast.resent"),
},
);
- else
+ else if (v === "cancel" && canCancelInvitations)
void run(() => api.cancelInvitation(inv.id), {
success: t("mobile:members.toast.canceled"),
});
diff --git a/apps/mobile/src/app/(app)/workspace/[workspaceId]/settings.tsx b/apps/mobile/src/app/(app)/workspace/[workspaceId]/settings.tsx
index 4b9b2ab92..dceaf37b2 100644
--- a/apps/mobile/src/app/(app)/workspace/[workspaceId]/settings.tsx
+++ b/apps/mobile/src/app/(app)/workspace/[workspaceId]/settings.tsx
@@ -17,11 +17,15 @@ import { Txt } from "@/components/text";
import { Button, Group, GroupRow, Section, TextField } from "@/components/ui";
import { userMessage } from "@/lib/api/client";
import { api } from "@/lib/api/endpoints";
-import { workspaceDescription } from "@/lib/describe";
import { useWorkspaceLabels, useWorkspaces } from "@/lib/hooks";
import { qk, useAction } from "@/lib/query";
import { sessionStore, useRequiredSession } from "@/lib/session";
-import { canManageWorkspace, hasRole } from "@/lib/style";
+import { hasRole } from "@/lib/style";
+import { useWorkspaceCapabilities } from "@/lib/use-workspace-capabilities";
+import {
+ getWorkspaceDescription,
+ workspaceDescriptionUpdate,
+} from "@/lib/workspace-description";
import { useColors } from "@/theme";
export default function WorkspaceSettingsScreen() {
@@ -40,13 +44,16 @@ export default function WorkspaceSettingsScreen() {
const role =
workspace?.role ??
org.data?.members?.find((m) => m.userId === session.userId)?.role;
- const canEdit = canManageWorkspace(role);
+ const capabilities = useWorkspaceCapabilities(workspaceId);
+ const canEdit = capabilities.data?.manageWorkspace === true;
+ const canDelete = capabilities.data?.deleteWorkspace === true;
const isOwner = hasRole(role, "owner");
const [confirm, setConfirm] = useState<"leave" | "delete" | null>(null);
const workspaceName =
workspace?.name ?? t("mobile:workspaceSettings.thisWorkspace");
const leaveOrDelete = async (kind: "leave" | "delete") => {
+ if (kind === "delete" && !canDelete) return;
const ok = await run(
() =>
kind === "delete"
@@ -69,8 +76,11 @@ export default function WorkspaceSettingsScreen() {
<Screen>
<Scroll
bottomPadding={40}
- refreshing={org.isRefetching}
- onRefresh={() => void org.refetch()}
+ refreshing={org.isRefetching || capabilities.isRefetching}
+ onRefresh={() => {
+ void org.refetch();
+ void capabilities.refetch();
+ }}
>
<PageHeader
title={t("mobile:workspaceSettings.title")}
@@ -94,16 +104,20 @@ export default function WorkspaceSettingsScreen() {
<GeneralForm
key={`${org.data.id}-${org.data.name}`}
name={org.data.name}
- description={workspaceDescription(org.data.metadata)}
+ description={getWorkspaceDescription(org.data)}
slug={org.data.slug}
canEdit={canEdit}
busy={busy}
onSave={(name, description) =>
+ canEdit &&
run(
() =>
api.updateWorkspace(workspaceId, {
name,
- metadata: { description },
+ ...workspaceDescriptionUpdate(
+ description,
+ org.data.metadata,
+ ),
}),
{ success: t("mobile:workspaceSettings.toast.updated") },
)
@@ -153,7 +167,7 @@ export default function WorkspaceSettingsScreen() {
<Section title={t("mobile:workspaceSettings.danger.title")}>
<Group>
{!isOwner ? (
- <GroupRow last={!isOwner}>
+ <GroupRow last={!canDelete}>
<View style={{ flex: 1, gap: 2 }}>
<Txt variant="body">
{t("mobile:workspaceSettings.danger.leave")}
@@ -170,7 +184,7 @@ export default function WorkspaceSettingsScreen() {
/>
</GroupRow>
) : null}
- {isOwner ? (
+ {canDelete ? (
<GroupRow last>
<View style={{ flex: 1, gap: 2 }}>
<Txt variant="body">
@@ -194,7 +208,7 @@ export default function WorkspaceSettingsScreen() {
)}
</Scroll>
<ConfirmDialog
- visible={!!confirm}
+ visible={!!confirm && (confirm !== "delete" || canDelete)}
title={
confirm === "delete"
? t("mobile:workspaceSettings.confirm.deleteTitle")
@@ -266,7 +280,7 @@ function GeneralForm({
label={t("mobile:workspaceSettings.general.save")}
size="md"
loading={busy}
- disabled={!name.trim()}
+ disabled={busy || !name.trim()}
onPress={() => onSave(name.trim(), description.trim())}
/>
</View>
diff --git a/apps/mobile/src/components/notification-opener.tsx b/apps/mobile/src/components/notification-opener.tsx
index 583663f12..fbceb9de6 100644
--- a/apps/mobile/src/components/notification-opener.tsx
+++ b/apps/mobile/src/components/notification-opener.tsx
@@ -1,12 +1,20 @@
import * as Notifications from "expo-notifications";
import { router } from "expo-router";
-import { useEffect } from "react";
+import { useEffect, useRef } from "react";
/** Opens the task behind a tapped system notification. */
export function NotificationOpener({ enabled }: { enabled: boolean }) {
const response = Notifications.useLastNotificationResponse();
+ const handled = useRef<string | null>(null);
useEffect(() => {
- const taskId = response?.notification.request.content.data?.taskId;
+ if (!response) return;
+ const id = response.notification.request.identifier;
+ if (handled.current === id) return;
+ // Handle each tap once, and drop taps made while signed out, so a later sign-in never
+ // replays a notification from an earlier session.
+ handled.current = id;
+ Notifications.clearLastNotificationResponse();
+ const taskId = response.notification.request.content.data?.taskId;
if (enabled && typeof taskId === "string")
router.push({ pathname: "/task/[taskId]", params: { taskId } });
}, [response, enabled]);
diff --git a/apps/mobile/src/features/project/custom-field-default-input.tsx b/apps/mobile/src/features/project/custom-field-default-input.tsx
new file mode 100644
index 000000000..abae39b75
--- /dev/null
+++ b/apps/mobile/src/features/project/custom-field-default-input.tsx
@@ -0,0 +1,103 @@
+import { useState } from "react";
+import { useTranslation } from "react-i18next";
+import { View } from "react-native";
+
+import { DatePickerSheet } from "@/components/pickers";
+import { MultiSelectSheet, OptionSheet } from "@/components/sheet";
+import { Txt } from "@/components/text";
+import { Button, TextField } from "@/components/ui";
+import { formatDate, toIsoDay } from "@/lib/format";
+
+import { selectedDefaults, type CustomFieldType } from "./field-form";
+
+export function CustomFieldDefaultInput({
+ type,
+ value,
+ options,
+ onChange,
+}: {
+ type: CustomFieldType;
+ value: string;
+ options: string[];
+ onChange: (value: string) => void;
+}) {
+ const { t } = useTranslation(["mobile"]);
+ const [picking, setPicking] = useState(false);
+ const label = t("mobile:projectSettings.defaultValue");
+
+ if (type === "text" || type === "number") {
+ return (
+ <TextField
+ label={label}
+ accessibilityLabel={label}
+ value={value}
+ onChangeText={onChange}
+ keyboardType={type === "number" ? "numbers-and-punctuation" : "default"}
+ autoCapitalize="none"
+ autoCorrect={false}
+ />
+ );
+ }
+
+ const booleanOptions = [
+ { value: "false", label: t("mobile:projectSettings.unchecked") },
+ { value: "true", label: t("mobile:projectSettings.checked") },
+ ];
+ const selected = selectedDefaults(value);
+ const display =
+ type === "date"
+ ? formatDate(value)
+ : type === "boolean"
+ ? booleanOptions.find((option) => option.value === value)?.label
+ : type === "multiselect"
+ ? selected.join(", ")
+ : value;
+
+ return (
+ <View style={{ gap: 8 }}>
+ <Txt variant="meta" weight="medium" tone="body">
+ {label}
+ </Txt>
+ <Button
+ label={display || t("mobile:projectSettings.chooseDefault")}
+ kind="secondary"
+ disabled={
+ (type === "dropdown" || type === "multiselect") &&
+ options.length === 0
+ }
+ onPress={() => setPicking(true)}
+ />
+ {type === "date" ? (
+ <DatePickerSheet
+ visible={picking}
+ onClose={() => setPicking(false)}
+ title={label}
+ value={value}
+ onPick={(day) => onChange(day ? toIsoDay(day) : "")}
+ />
+ ) : type === "multiselect" ? (
+ <MultiSelectSheet
+ visible={picking}
+ onClose={() => setPicking(false)}
+ title={label}
+ options={options}
+ selected={selected.filter((option) => options.includes(option))}
+ onSave={(values) => onChange(JSON.stringify(values))}
+ />
+ ) : (
+ <OptionSheet
+ visible={picking}
+ onClose={() => setPicking(false)}
+ title={label}
+ options={
+ type === "boolean"
+ ? booleanOptions
+ : options.map((option) => ({ value: option, label: option }))
+ }
+ selected={value}
+ onSelect={onChange}
+ />
+ )}
+ </View>
+ );
+}
diff --git a/apps/mobile/src/features/project/custom-field-form.tsx b/apps/mobile/src/features/project/custom-field-form.tsx
new file mode 100644
index 000000000..4ce417d0b
--- /dev/null
+++ b/apps/mobile/src/features/project/custom-field-form.tsx
@@ -0,0 +1,139 @@
+import { useState } from "react";
+import { useTranslation } from "react-i18next";
+import { View } from "react-native";
+
+import { Txt } from "@/components/text";
+import { Button, Chip, Switch, TextField } from "@/components/ui";
+
+import { CustomFieldDefaultInput } from "./custom-field-default-input";
+import {
+ canSaveField,
+ fieldOptions,
+ toCreateFieldBody,
+ validFieldDefault,
+ type CreateFieldBody,
+ type FieldForm,
+} from "./field-form";
+import { useFieldTypes } from "./use-field-types";
+
+export function CustomFieldForm({
+ onClose,
+ onAdd,
+ busy,
+}: {
+ onClose: () => void;
+ onAdd: (body: CreateFieldBody) => Promise<unknown | undefined>;
+ busy: boolean;
+}) {
+ const { t } = useTranslation(["mobile"]);
+ const fieldTypes = useFieldTypes();
+ const [form, setForm] = useState<FieldForm>({
+ name: "",
+ type: "text",
+ optionsText: "",
+ required: false,
+ defaultValue: "",
+ });
+ const { name, type, optionsText, required, defaultValue } = form;
+ const needsOptions = type === "dropdown" || type === "multiselect";
+ const options = fieldOptions(optionsText);
+ const valid = canSaveField(form);
+ const submit = async () => {
+ if (!valid || busy) return;
+ const result = await onAdd(toCreateFieldBody(form));
+ if (result !== undefined) onClose();
+ };
+
+ return (
+ <View style={{ paddingHorizontal: 20, paddingBottom: 12, gap: 16 }}>
+ <TextField
+ label={t("mobile:projectSettings.name")}
+ value={name}
+ onChangeText={(name) => setForm((current) => ({ ...current, name }))}
+ placeholder={t("mobile:projectSettings.platform")}
+ autoFocus
+ />
+ <View style={{ gap: 8 }}>
+ <Txt variant="meta" weight="medium" tone="body">
+ {t("mobile:projectSettings.type")}
+ </Txt>
+ <View style={{ flexDirection: "row", flexWrap: "wrap", gap: 6 }}>
+ {fieldTypes.map((fieldType) => (
+ <Chip
+ key={fieldType.value}
+ label={fieldType.label}
+ selected={type === fieldType.value}
+ onPress={() =>
+ setForm((current) =>
+ current.type === fieldType.value
+ ? current
+ : {
+ ...current,
+ type: fieldType.value,
+ defaultValue:
+ fieldType.value === "boolean" ? "false" : "",
+ },
+ )
+ }
+ />
+ ))}
+ </View>
+ </View>
+ {needsOptions ? (
+ <TextField
+ label={t("mobile:projectSettings.options")}
+ aside={t("mobile:projectSettings.separateWithCommas")}
+ value={optionsText}
+ onChangeText={(optionsText) =>
+ setForm((current) => ({ ...current, optionsText }))
+ }
+ placeholder={t("mobile:projectSettings.androidIOSWeb")}
+ hint={
+ type === "multiselect" && options.length < 2
+ ? t("mobile:projectSettings.multiselectOptionsRequired")
+ : undefined
+ }
+ />
+ ) : null}
+ <View
+ style={{
+ flexDirection: "row",
+ alignItems: "center",
+ justifyContent: "space-between",
+ }}
+ >
+ <Txt variant="bodySm">{t("mobile:projectSettings.required")}</Txt>
+ <Switch
+ value={required}
+ onChange={(required) =>
+ setForm((current) => ({ ...current, required }))
+ }
+ />
+ </View>
+ {required ? (
+ <>
+ <CustomFieldDefaultInput
+ key={type}
+ type={type}
+ value={defaultValue}
+ options={options}
+ onChange={(defaultValue) =>
+ setForm((current) => ({ ...current, defaultValue }))
+ }
+ />
+ {!validFieldDefault(type, defaultValue, options) ? (
+ <Txt variant="caption" tone="faint">
+ {t("mobile:projectSettings.validDefaultRequired")}
+ </Txt>
+ ) : null}
+ </>
+ ) : null}
+ <Button
+ label={t("mobile:projectSettings.addField")}
+ disabled={!valid}
+ loading={busy}
+ onPress={() => void submit()}
+ />
+ </View>
+ );
+}
diff --git a/apps/mobile/src/features/project/field-form.test.ts b/apps/mobile/src/features/project/field-form.test.ts
new file mode 100644
index 000000000..93ef3b58e
--- /dev/null
+++ b/apps/mobile/src/features/project/field-form.test.ts
@@ -0,0 +1,169 @@
+import { describe, expect, it } from "vite-plus/test";
+
+import {
+ canSaveField,
+ fieldOptions,
+ toCreateFieldBody,
+ validFieldDefault,
+ type CustomFieldType,
+ type FieldForm,
+} from "./field-form";
+
+const form: FieldForm = {
+ name: " Platform ",
+ type: "text",
+ required: true,
+ optionsText: "Android, iOS",
+ defaultValue: "Android",
+};
+
+describe("required custom field defaults", () => {
+ it.each<CustomFieldType>([
+ "text",
+ "number",
+ "date",
+ "boolean",
+ "dropdown",
+ "multiselect",
+ ])("rejects missing and blank defaults for %s", (type) => {
+ expect(canSaveField({ ...form, type, defaultValue: "" })).toBe(false);
+ expect(canSaveField({ ...form, type, defaultValue: " " })).toBe(false);
+ });
+
+ it.each([
+ ["0", true],
+ ["-1.25", true],
+ [" 2e+3 ", true],
+ ["1e999", false],
+ ["Infinity", false],
+ ["NaN", false],
+ ["0x10", false],
+ [".5", false],
+ ["1.", false],
+ ["1,5", false],
+ ["1e", false],
+ ["12px", false],
+ ])("validates numeric default %s", (value, valid) => {
+ expect(validFieldDefault("number", value, [])).toBe(valid);
+ });
+
+ it.each([
+ ["2024-02-29", true],
+ ["2026-10-17", true],
+ ["2026-10-17T12:30:00.000Z", true],
+ ["2025-02-29", false],
+ ["2026-02-30", false],
+ ["2026-13-01", false],
+ ["2026-00-01", false],
+ ["10/17/2026", false],
+ ["2026-10-17T25:00:00Z", false],
+ ])("validates calendar default %s", (value, valid) => {
+ expect(validFieldDefault("date", value, [])).toBe(valid);
+ });
+
+ it("accepts both boolean states, including unchecked", () => {
+ expect(validFieldDefault("boolean", "true", [])).toBe(true);
+ expect(
+ canSaveField({ ...form, type: "boolean", defaultValue: "false" }),
+ ).toBe(true);
+ expect(validFieldDefault("boolean", "yes", [])).toBe(false);
+ });
+
+ it("requires dropdown defaults to match a current option", () => {
+ expect(canSaveField({ ...form, type: "dropdown" })).toBe(true);
+ expect(
+ canSaveField({ ...form, type: "dropdown", optionsText: "iOS" }),
+ ).toBe(false);
+ });
+
+ it.each([
+ ['["Android"]', true],
+ ['["Android","iOS"]', true],
+ ["[]", false],
+ ["Android", false],
+ ['"Android"', false],
+ ['["Web"]', false],
+ ['["Android",1]', false],
+ ["null", false],
+ ])("validates multiselect default %s", (value, valid) => {
+ expect(validFieldDefault("multiselect", value, ["Android", "iOS"])).toBe(
+ valid,
+ );
+ });
+
+ it("requires two distinct multiselect options even for optional fields", () => {
+ expect(fieldOptions(" Android, Android, , iOS ")).toEqual([
+ "Android",
+ "iOS",
+ ]);
+ expect(
+ canSaveField({
+ ...form,
+ type: "multiselect",
+ required: false,
+ optionsText: "Android, Android",
+ }),
+ ).toBe(false);
+ expect(
+ canSaveField({
+ ...form,
+ type: "dropdown",
+ required: false,
+ optionsText: "",
+ }),
+ ).toBe(false);
+ });
+
+ it("checks defaults when Required is switched on", () => {
+ expect(canSaveField({ ...form, required: false, defaultValue: "" })).toBe(
+ true,
+ );
+ expect(canSaveField({ ...form, required: true, defaultValue: "" })).toBe(
+ false,
+ );
+ expect(canSaveField({ ...form, name: " " })).toBe(false);
+ });
+});
+
+describe("create payload", () => {
+ it("includes a typed default for each required field", () => {
+ const defaults: [CustomFieldType, string][] = [
+ ["text", " Android "],
+ ["number", "0"],
+ ["date", "2026-10-17"],
+ ["boolean", "false"],
+ ["dropdown", "Android"],
+ ["multiselect", '["Android"]'],
+ ];
+ for (const [type, defaultValue] of defaults) {
+ const current = { ...form, type, defaultValue };
+ expect(canSaveField(current)).toBe(true);
+ expect(toCreateFieldBody(current)).toMatchObject({
+ name: "Platform",
+ type,
+ required: true,
+ defaultValue,
+ });
+ }
+ });
+
+ it("omits the hidden default after Required is switched off", () => {
+ expect(
+ toCreateFieldBody({ ...form, required: false }).defaultValue,
+ ).toBeUndefined();
+ });
+
+ it("sends normalized options and trims non-text defaults", () => {
+ expect(
+ toCreateFieldBody({
+ ...form,
+ type: "dropdown",
+ defaultValue: " Android ",
+ optionsText: " Android, Android, iOS, ",
+ }),
+ ).toMatchObject({
+ options: ["Android", "iOS"],
+ defaultValue: "Android",
+ });
+ });
+});
diff --git a/apps/mobile/src/features/project/field-form.ts b/apps/mobile/src/features/project/field-form.ts
new file mode 100644
index 000000000..3e434a1ab
--- /dev/null
+++ b/apps/mobile/src/features/project/field-form.ts
@@ -0,0 +1,120 @@
+export type CustomFieldType =
+ | "text"
+ | "number"
+ | "date"
+ | "boolean"
+ | "dropdown"
+ | "multiselect";
+
+export type FieldForm = {
+ name: string;
+ type: CustomFieldType;
+ optionsText: string;
+ required: boolean;
+ defaultValue: string;
+};
+
+export type CreateFieldBody = {
+ name: string;
+ type: CustomFieldType;
+ required: boolean;
+ options?: string[];
+ defaultValue?: string;
+};
+
+export function fieldOptions(text: string): string[] {
+ return [
+ ...new Set(
+ text
+ .split(",")
+ .map((option) => option.trim())
+ .filter(Boolean),
+ ),
+ ];
+}
+
+export function selectedDefaults(value: string): string[] {
+ try {
+ const parsed: unknown = JSON.parse(value);
+ return Array.isArray(parsed) &&
+ parsed.every((item) => typeof item === "string")
+ ? parsed
+ : [];
+ } catch {
+ return [];
+ }
+}
+
+export function validFieldDefault(
+ type: CustomFieldType,
+ value: string,
+ options: string[],
+): boolean {
+ const trimmed = value.trim();
+ if (!trimmed) return false;
+
+ switch (type) {
+ case "number":
+ return (
+ /^-?\d+(?:\.\d+)?(?:e[+-]?\d+)?$/i.test(trimmed) &&
+ Number.isFinite(Number(trimmed))
+ );
+ case "boolean":
+ return trimmed === "true" || trimmed === "false";
+ case "dropdown":
+ return options.includes(trimmed);
+ case "multiselect": {
+ const values = selectedDefaults(trimmed);
+ return (
+ values.length > 0 && values.every((option) => options.includes(option))
+ );
+ }
+ case "date": {
+ const match =
+ /^(\d{4})-(\d{2})-(\d{2})(T\d{2}:\d{2}:\d{2}(\.\d{3})?(Z|[+-]\d{2}:\d{2})?)?$/.exec(
+ trimmed,
+ );
+ if (!match || Number.isNaN(Date.parse(trimmed))) return false;
+ const year = Number(match[1]);
+ const month = Number(match[2]);
+ const day = Number(match[3]);
+ const date = new Date(0);
+ date.setUTCFullYear(year, month - 1, day);
+ date.setUTCHours(0, 0, 0, 0);
+ return (
+ date.getUTCFullYear() === year &&
+ date.getUTCMonth() === month - 1 &&
+ date.getUTCDate() === day
+ );
+ }
+ case "text":
+ return true;
+ }
+}
+
+export function canSaveField(form: FieldForm): boolean {
+ const options = fieldOptions(form.optionsText);
+ if (!form.name.trim()) return false;
+ if (form.type === "dropdown" && options.length < 1) return false;
+ if (form.type === "multiselect" && options.length < 2) return false;
+ return (
+ !form.required || validFieldDefault(form.type, form.defaultValue, options)
+ );
+}
+
+export function toCreateFieldBody(form: FieldForm): CreateFieldBody {
+ return {
+ name: form.name.trim(),
+ type: form.type,
+ required: form.required,
+ options:
+ form.type === "dropdown" || form.type === "multiselect"
+ ? fieldOptions(form.optionsText)
+ : undefined,
+ defaultValue: form.required
+ ? form.type === "text"
+ ? form.defaultValue
+ : form.defaultValue.trim()
+ : undefined,
+ };
+}
diff --git a/apps/mobile/src/features/project/use-field-types.ts b/apps/mobile/src/features/project/use-field-types.ts
new file mode 100644
index 000000000..b6c9f043f
--- /dev/null
+++ b/apps/mobile/src/features/project/use-field-types.ts
@@ -0,0 +1,13 @@
+import { useTranslation } from "react-i18next";
+
+export function useFieldTypes() {
+ const { t } = useTranslation(["mobile"]);
+ return [
+ { value: "text", label: t("mobile:projectSettings.text") },
+ { value: "number", label: t("mobile:projectSettings.number") },
+ { value: "date", label: t("mobile:projectSettings.date") },
+ { value: "boolean", label: t("mobile:projectSettings.checkbox") },
+ { value: "dropdown", label: t("mobile:projectSettings.dropdown") },
+ { value: "multiselect", label: t("mobile:projectSettings.multiSelect") },
+ ] as const;
+}
diff --git a/apps/mobile/src/features/task/new-task-fields.test.ts b/apps/mobile/src/features/task/new-task-fields.test.ts
new file mode 100644
index 000000000..c3c1e9ec8
--- /dev/null
+++ b/apps/mobile/src/features/task/new-task-fields.test.ts
@@ -0,0 +1,67 @@
+import { describe, expect, it } from "vite-plus/test";
+import {
+ customFieldsPayload,
+ draftFieldValues,
+ hasMissingRequired,
+ isFieldValueEmpty,
+} from "./new-task-fields";
+
+const field = (
+ id: string,
+ type: string,
+ required = false,
+ defaultValue: string | null = null,
+) => ({ id, type, required, defaultValue });
+
+describe("isFieldValueEmpty", () => {
+ it("treats blanks and empty multiselects as empty", () => {
+ expect(isFieldValueEmpty(undefined, "number")).toBe(true);
+ expect(isFieldValueEmpty(" ", "number")).toBe(true);
+ expect(isFieldValueEmpty("[]", "multiselect")).toBe(true);
+ expect(isFieldValueEmpty('["a"]', "multiselect")).toBe(false);
+ expect(isFieldValueEmpty("false", "boolean")).toBe(false);
+ });
+});
+
+describe("draftFieldValues", () => {
+ it("seeds defaults and keeps the person's edits over them", () => {
+ const fields = [
+ field("size", "number", true, "3"),
+ field("tags", "multiselect", false, '["a"]'),
+ field("due", "date"),
+ ];
+ expect(draftFieldValues(fields, {})).toEqual({ size: "3", tags: '["a"]' });
+ expect(draftFieldValues(fields, { size: "5", tags: "[]" })).toEqual({
+ size: "5",
+ tags: "[]",
+ });
+ });
+
+ it("ignores empty defaults and saves an untouched required switch as off", () => {
+ const fields = [
+ field("tags", "multiselect", true, "[]"),
+ field("done", "boolean", true),
+ field("flag", "boolean"),
+ ];
+ expect(draftFieldValues(fields, {})).toEqual({ done: "false" });
+ });
+});
+
+describe("hasMissingRequired", () => {
+ it("is satisfied by a valid default", () => {
+ const fields = [field("size", "number", true, "3")];
+ expect(hasMissingRequired(fields, draftFieldValues(fields, {}))).toBe(
+ false,
+ );
+ expect(hasMissingRequired(fields, { size: "" })).toBe(true);
+ });
+});
+
+describe("customFieldsPayload", () => {
+ it("sends only non-empty values of the project's fields", () => {
+ const fields = [field("a", "number"), field("b", "multiselect")];
+ expect(customFieldsPayload(fields, { a: "1", b: "[]", c: "x" })).toEqual([
+ { fieldId: "a", value: "1" },
+ ]);
+ });
+});
diff --git a/apps/mobile/src/features/task/new-task-fields.ts b/apps/mobile/src/features/task/new-task-fields.ts
new file mode 100644
index 000000000..c07ef8454
--- /dev/null
+++ b/apps/mobile/src/features/task/new-task-fields.ts
@@ -0,0 +1,61 @@
+import type { CustomFieldDefinition } from "@/lib/api/types";
+
+type Field = Pick<
+ CustomFieldDefinition,
+ "id" | "type" | "required" | "defaultValue"
+>;
+
+/** Same rule as the API's `isCustomFieldValueEmpty`: blank, or an empty multiselect array. */
+export function isFieldValueEmpty(
+ value: string | null | undefined,
+ type: string,
+) {
+ if (!value?.trim()) return true;
+ if (type !== "multiselect") return false;
+ try {
+ const parsed: unknown = JSON.parse(value);
+ return Array.isArray(parsed) && parsed.length === 0;
+ } catch {
+ return false;
+ }
+}
+
+/**
+ * The values a new task would get: the person's edits, else each field's default (the API
+ * applies required defaults anyway, and the web form seeds them all). An untouched required
+ * switch saves as off, which is what it shows.
+ */
+export function draftFieldValues(
+ fields: Field[],
+ edits: Record<string, string>,
+): Record<string, string> {
+ const values: Record<string, string> = {};
+ for (const f of fields) {
+ const value =
+ edits[f.id] ??
+ (isFieldValueEmpty(f.defaultValue, f.type)
+ ? undefined
+ : f.defaultValue) ??
+ (f.required && f.type === "boolean" ? "false" : undefined);
+ if (value != null) values[f.id] = value;
+ }
+ return values;
+}
+
+export function hasMissingRequired(
+ fields: Field[],
+ values: Record<string, string>,
+) {
+ return fields.some(
+ (f) => f.required && isFieldValueEmpty(values[f.id], f.type),
+ );
+}
+
+export function customFieldsPayload(
+ fields: Field[],
+ values: Record<string, string>,
+) {
+ return fields
+ .filter((f) => !isFieldValueEmpty(values[f.id], f.type))
+ .map((f) => ({ fieldId: f.id, value: values[f.id]! }));
+}
diff --git a/apps/mobile/src/lib/api/endpoints.ts b/apps/mobile/src/lib/api/endpoints.ts
index dd147ed85..db86b076e 100644
--- a/apps/mobile/src/lib/api/endpoints.ts
+++ b/apps/mobile/src/lib/api/endpoints.ts
@@ -27,6 +27,7 @@ import type {
UpdateTaskBody,
Workspace,
WorkspaceActivity,
+ WorkspaceCapabilities,
WorkspaceMember,
} from "./types";
@@ -77,6 +78,16 @@ export const api = {
return get<Workspace[]>("api/auth/organization/list");
throw e;
}),
+ workspaceCapabilities: (workspaceId: string) =>
+ get<WorkspaceCapabilities>(`api/workspace/${workspaceId}/capabilities`),
+ workspacePermission: (
+ organizationId: string,
+ permissions: Record<string, string[]>,
+ ) =>
+ post<{ success: boolean }>("api/auth/organization/has-permission", {
+ organizationId,
+ permissions,
+ }),
workspaceMembers: (workspaceId: string, projectId?: string) =>
get<WorkspaceMember[]>(`api/workspace/${workspaceId}/members`, {
projectId,
@@ -88,8 +99,17 @@ export const api = {
}) => post<Workspace>("api/auth/organization/create", body),
updateWorkspace: (
organizationId: string,
- data: { name?: string; metadata?: Record<string, string> },
- ) => post<unknown>("api/auth/organization/update", { organizationId, data }),
+ data: {
+ name?: string;
+ description?: string;
+ metadata?: Record<string, Json>;
+ },
+ ) =>
+ request<unknown>("api/auth/organization/update", {
+ method: "POST",
+ body: { organizationId, data },
+ keepNulls: true,
+ }),
deleteWorkspace: (organizationId: string) =>
post<unknown>("api/auth/organization/delete", { organizationId }),
leaveWorkspace: (organizationId: string) =>
@@ -322,6 +342,7 @@ export const api = {
name: string;
type: string;
required: boolean;
+ defaultValue?: string;
options?: string[];
}) => post<unknown>("api/custom-field", body),
deleteCustomField: (id: string) => del<unknown>(`api/custom-field/${id}`),
diff --git a/apps/mobile/src/lib/api/types.ts b/apps/mobile/src/lib/api/types.ts
index 457a7f3e3..e08a23e37 100644
--- a/apps/mobile/src/lib/api/types.ts
+++ b/apps/mobile/src/lib/api/types.ts
@@ -57,9 +57,33 @@ export type Workspace = {
logo?: string | null;
createdAt?: string | null;
role?: string | null;
+ description?: string | null;
metadata?: Json;
};
+export type WorkspaceCapabilities = Record<
+ | "manageProjects"
+ | "createProjects"
+ | "updateProjects"
+ | "shareProjects"
+ | "deleteProjects"
+ | "updateTasks"
+ | "createTasks"
+ | "deleteTasks"
+ | "assignTasks"
+ | "createLabels"
+ | "updateLabels"
+ | "deleteLabels"
+ | "manageWorkspace"
+ | "manageSettings"
+ | "deleteWorkspace"
+ | "inviteUsers"
+ | "manageTeam"
+ | "updateMembers"
+ | "removeMembers",
+ boolean
+>;
+
export type WorkspaceMember = {
id: string;
name: string;
@@ -92,6 +116,7 @@ export type FullOrganization = {
id: string;
name: string;
slug: string;
+ description?: string | null;
metadata?: Json;
members?: OrganizationMember[];
invitations?: OrganizationInvitation[];
diff --git a/apps/mobile/src/lib/query.ts b/apps/mobile/src/lib/query.ts
index 0b5fe9981..0de048b25 100644
--- a/apps/mobile/src/lib/query.ts
+++ b/apps/mobile/src/lib/query.ts
@@ -36,6 +36,9 @@ export const qk = {
customFields: (projectId: string) => ["customFields", projectId] as const,
fullWorkspace: (id: string) => ["fullWorkspace", id] as const,
roles: (id: string) => ["roles", id] as const,
+ capabilities: (workspaceId: string) => ["capabilities", workspaceId] as const,
+ canCancelInvitations: (workspaceId: string) =>
+ ["canCancelInvitations", workspaceId] as const,
notificationPrefs: ["notificationPrefs"] as const,
search: (workspaceId: string, q: string, type: string) =>
["search", workspaceId, q, type] as const,
diff --git a/apps/mobile/src/lib/realtime-connection.test.ts b/apps/mobile/src/lib/realtime-connection.test.ts
new file mode 100644
index 000000000..c11d844d8
--- /dev/null
+++ b/apps/mobile/src/lib/realtime-connection.test.ts
@@ -0,0 +1,118 @@
+import {
+ afterEach,
+ beforeEach,
+ describe,
+ expect,
+ it,
+ vi,
+} from "vite-plus/test";
+
+import {
+ createRealtimeConnection,
+ type RealtimeSocket,
+} from "./realtime-connection";
+
+class FakeSocket implements RealtimeSocket {
+ onopen: (() => void) | null = null;
+ onmessage: ((message: { data: unknown }) => void) | null = null;
+ onclose: (() => void) | null = null;
+ onerror: (() => void) | null = null;
+ sent: string[] = [];
+ closed = false;
+ send(data: string) {
+ this.sent.push(data);
+ }
+ close() {
+ this.closed = true;
+ }
+}
+
+function setup() {
+ const sockets: FakeSocket[] = [];
+ const events: unknown[] = [];
+ const connection = createRealtimeConnection(
+ () => {
+ const socket = new FakeSocket();
+ sockets.push(socket);
+ return socket;
+ },
+ (event) => events.push(event),
+ );
+ return { sockets, events, connection };
+}
+
+beforeEach(() => {
+ vi.useFakeTimers();
+});
+afterEach(() => {
+ vi.useRealTimers();
+});
+
+describe("createRealtimeConnection", () => {
+ it("passes on events and skips keepalive replies and non-JSON frames", () => {
+ const { sockets, events, connection } = setup();
+ connection.start();
+ sockets[0].onmessage?.({ data: '{"type":"pong"}' });
+ sockets[0].onmessage?.({ data: "hello" });
+ sockets[0].onmessage?.({ data: '{"type":"task.updated","taskId":"t1"}' });
+ expect(events).toEqual([{ type: "task.updated", taskId: "t1" }]);
+ });
+
+ it("sends a keepalive while open", () => {
+ const { sockets, connection } = setup();
+ connection.start();
+ sockets[0].onopen?.();
+ vi.advanceTimersByTime(30_000);
+ expect(sockets[0].sent).toEqual(['{"type":"ping"}']);
+ });
+
+ it("reconnects with backoff after the server closes the socket", () => {
+ const { sockets, connection } = setup();
+ connection.start();
+ sockets[0].onclose?.();
+ vi.advanceTimersByTime(1_999);
+ expect(sockets).toHaveLength(1);
+ vi.advanceTimersByTime(1);
+ expect(sockets).toHaveLength(2);
+ });
+
+ it("ignores a late close from a stopped socket after restarting", () => {
+ const { sockets, events, connection } = setup();
+ connection.start();
+ const old = sockets[0];
+ const oldClose = old.onclose;
+ const oldMessage = old.onmessage;
+ connection.stop();
+ expect(old.closed).toBe(true);
+
+ connection.start();
+ sockets[1].onopen?.();
+ // The old socket's close event arrives after the new socket opened.
+ oldClose?.();
+ oldMessage?.({ data: '{"type":"task.updated"}' });
+ vi.advanceTimersByTime(60_000);
+
+ expect(sockets).toHaveLength(2);
+ expect(events).toEqual([]);
+ // The new socket's keepalive survives.
+ expect(sockets[1].sent).toEqual(['{"type":"ping"}', '{"type":"ping"}']);
+ });
+
+ it("cancels a pending reconnect when stopped", () => {
+ const { sockets, connection } = setup();
+ connection.start();
+ sockets[0].onclose?.();
+ connection.stop();
+ vi.advanceTimersByTime(60_000);
+ expect(sockets).toHaveLength(1);
+ });
+
+ it("replaces a pending reconnect instead of adding a socket when started", () => {
+ const { sockets, connection } = setup();
+ connection.start();
+ sockets[0].onclose?.();
+ connection.start();
+ vi.advanceTimersByTime(60_000);
+ expect(sockets).toHaveLength(2);
+ });
+});
diff --git a/apps/mobile/src/lib/realtime-connection.ts b/apps/mobile/src/lib/realtime-connection.ts
new file mode 100644
index 000000000..991a46ce1
--- /dev/null
+++ b/apps/mobile/src/lib/realtime-connection.ts
@@ -0,0 +1,94 @@
+export type RealtimeEvent = {
+ type: string;
+ projectId?: string;
+ taskId?: string;
+};
+
+/** The part of WebSocket the connection uses, so tests can pass a fake. */
+export type RealtimeSocket = {
+ onopen: (() => void) | null;
+ onmessage: ((message: { data: unknown }) => void) | null;
+ onclose: (() => void) | null;
+ onerror: (() => void) | null;
+ send(data: string): void;
+ close(): void;
+};
+
+function parseEvent(data: unknown): RealtimeEvent | null {
+ try {
+ const event = JSON.parse(String(data)) as RealtimeEvent;
+ return event?.type && event.type !== "PING" && event.type !== "pong"
+ ? event
+ : null;
+ } catch {
+ // Ignore non-JSON frames.
+ return null;
+ }
+}
+
+/**
+ * Keeps one socket open between `start()` and `stop()`, reconnecting with backoff. Each socket
+ * owns its keepalive, and `stop()` detaches its handlers, so a close event that arrives late
+ * (common on iOS after a quick app switch) cannot touch the next socket or open a second one.
+ */
+export function createRealtimeConnection(
+ openSocket: () => RealtimeSocket,
+ onEvent: (event: RealtimeEvent) => void,
+) {
+ let current: { socket: RealtimeSocket; dispose: () => void } | null = null;
+ let retry: ReturnType<typeof setTimeout> | null = null;
+ let attempt = 0;
+
+ const connect = () => {
+ const socket = openSocket();
+ let keepAlive: ReturnType<typeof setInterval> | null = null;
+ const dispose = () => {
+ if (keepAlive) clearInterval(keepAlive);
+ keepAlive = null;
+ socket.onopen = socket.onmessage = socket.onclose = socket.onerror = null;
+ };
+ current = { socket, dispose };
+ socket.onopen = () => {
+ attempt = 0;
+ // The server only accepts this exact text keepalive.
+ keepAlive = setInterval(() => socket.send('{"type":"ping"}'), 30_000);
+ };
+ socket.onmessage = (message) => {
+ if (current?.socket !== socket) return;
+ const event = parseEvent(message.data);
+ if (event) onEvent(event);
+ };
+ socket.onclose = () => {
+ dispose();
+ if (current?.socket !== socket) return;
+ current = null;
+ attempt += 1;
+ retry = setTimeout(
+ () => {
+ retry = null;
+ connect();
+ },
+ Math.min(30_000, 2_000 * attempt),
+ );
+ };
+ socket.onerror = () => socket.close();
+ };
+
+ const stop = () => {
+ if (retry) clearTimeout(retry);
+ retry = null;
+ const last = current;
+ current = null;
+ last?.dispose();
+ last?.socket.close();
+ };
+
+ return {
+ start() {
+ stop();
+ attempt = 0;
+ connect();
+ },
+ stop,
+ };
+}
diff --git a/apps/mobile/src/lib/realtime.ts b/apps/mobile/src/lib/realtime.ts
index 64e134762..988236704 100644
--- a/apps/mobile/src/lib/realtime.ts
+++ b/apps/mobile/src/lib/realtime.ts
@@ -2,13 +2,14 @@ import { useEffect, useRef } from "react";
import { AppState } from "react-native";
import { credentialHeaders } from "./api/client";
+import {
+ createRealtimeConnection,
+ type RealtimeEvent,
+ type RealtimeSocket,
+} from "./realtime-connection";
import { useSession } from "./session";
-export type RealtimeEvent = {
- type: string;
- projectId?: string;
- taskId?: string;
-};
+export type { RealtimeEvent };
/**
* Kaneo pushes change hints over WebSockets: `/api/ws/user` for notifications and access changes,
@@ -27,70 +28,36 @@ export function useRealtime(
useEffect(() => {
if (!session || !path) return;
- let socket: WebSocket | null = null;
- let keepAlive: ReturnType<typeof setInterval> | null = null;
- let retry: ReturnType<typeof setTimeout> | null = null;
- let attempt = 0;
- let stopped = false;
-
- const connect = () => {
- if (stopped) return;
- // A per-connection windowId stops the server from treating this socket as the origin of
- // changes made by the same account elsewhere, which it would otherwise not echo.
- const windowId = `mobile-${Math.random().toString(36).slice(2)}`;
- const url = `${session.serverUrl.replace(/^http/, "ws")}/${path}?windowId=${windowId}`;
- // React Native's WebSocket accepts headers as a third argument; browsers ignore it.
- const Ctor = WebSocket as unknown as new (
- url: string,
- protocols?: string[] | null,
- options?: object,
- ) => WebSocket;
- socket = new Ctor(url, null, { headers: credentialHeaders(session) });
- socket.onopen = () => {
- attempt = 0;
- // The server only accepts this exact text keepalive.
- keepAlive = setInterval(() => socket?.send('{"type":"ping"}'), 30_000);
- };
- socket.onmessage = (message) => {
- try {
- const data = JSON.parse(String(message.data)) as RealtimeEvent;
- if (data?.type && data.type !== "PING" && data.type !== "pong")
- handler.current(data);
- } catch {
- // Ignore non-JSON frames.
- }
- };
- socket.onclose = () => {
- if (keepAlive) clearInterval(keepAlive);
- keepAlive = null;
- if (stopped) return;
- attempt += 1;
- retry = setTimeout(connect, Math.min(30_000, 2_000 * attempt));
- };
- socket.onerror = () => socket?.close();
- };
-
- const stop = () => {
- stopped = true;
- if (retry) clearTimeout(retry);
- if (keepAlive) clearInterval(keepAlive);
- socket?.close();
- socket = null;
- };
-
- connect();
+ const connection = createRealtimeConnection(
+ () => {
+ // A per-connection windowId stops the server from treating this socket as the origin of
+ // changes made by the same account elsewhere, which it would otherwise not echo.
+ const windowId = `mobile-${Math.random().toString(36).slice(2)}`;
+ const url = `${session.serverUrl.replace(/^http/, "ws")}/${path}?windowId=${windowId}`;
+ // React Native's WebSocket accepts headers as a third argument; browsers ignore it.
+ const Ctor = WebSocket as unknown as new (
+ url: string,
+ protocols?: string[] | null,
+ options?: object,
+ ) => RealtimeSocket;
+ return new Ctor(url, null, { headers: credentialHeaders(session) });
+ },
+ (event) => handler.current(event),
+ );
+ let running = true;
+ connection.start();
const sub = AppState.addEventListener("change", (state) => {
- if (state === "active" && stopped) {
- stopped = false;
- attempt = 0;
- connect();
+ if (state === "active" && !running) {
+ running = true;
+ connection.start();
} else if (state === "background") {
- stop();
+ running = false;
+ connection.stop();
}
});
return () => {
sub.remove();
- stop();
+ connection.stop();
};
}, [session, path]);
}
diff --git a/apps/mobile/src/lib/style.test.ts b/apps/mobile/src/lib/style.test.ts
index 6d535b6fd..2b4a9a682 100644
--- a/apps/mobile/src/lib/style.test.ts
+++ b/apps/mobile/src/lib/style.test.ts
@@ -1,6 +1,5 @@
import { describe, expect, it } from "vite-plus/test";
import {
- canManageWorkspace,
hasRole,
LABEL_COLORS,
priorityLabel,
@@ -16,14 +15,6 @@ describe("hasRole", () => {
});
});
-describe("canManageWorkspace", () => {
- it("allows owners and admins, even alongside other roles", () => {
- expect(canManageWorkspace("viewer,admin")).toBe(true);
- expect(canManageWorkspace("owner")).toBe(true);
- expect(canManageWorkspace("member,viewer")).toBe(false);
- });
-});
-
describe("roleLabel", () => {
it("labels known roles and joins comma-separated ones", () => {
expect(roleLabel("owner")).toBe("Owner");
diff --git a/apps/mobile/src/lib/style.ts b/apps/mobile/src/lib/style.ts
index 95559ff4f..f1a80f32b 100644
--- a/apps/mobile/src/lib/style.ts
+++ b/apps/mobile/src/lib/style.ts
@@ -158,9 +158,5 @@ export function hasRole(role: string | null | undefined, name: string) {
return !!role && role.split(",").includes(name);
}
-export function canManageWorkspace(role?: string | null) {
- return hasRole(role, "owner") || hasRole(role, "admin");
-}
-
export const STATUS_PLANNED = "planned";
export const STATUS_ARCHIVED = "archived";
diff --git a/apps/mobile/src/lib/use-workspace-capabilities.ts b/apps/mobile/src/lib/use-workspace-capabilities.ts
new file mode 100644
index 000000000..6406ab94b
--- /dev/null
+++ b/apps/mobile/src/lib/use-workspace-capabilities.ts
@@ -0,0 +1,23 @@
+import { useQuery } from "@tanstack/react-query";
+
+import { api } from "./api/endpoints";
+import { qk } from "./query";
+
+export function useWorkspaceCapabilities(workspaceId: string) {
+ return useQuery({
+ queryKey: qk.capabilities(workspaceId),
+ queryFn: () => api.workspaceCapabilities(workspaceId),
+ enabled: !!workspaceId,
+ });
+}
+
+// Cancellation has its own permission, absent from the named capabilities.
+export function useCanCancelInvitations(workspaceId: string) {
+ return useQuery({
+ queryKey: qk.canCancelInvitations(workspaceId),
+ queryFn: async () =>
+ (await api.workspacePermission(workspaceId, { invitation: ["cancel"] }))
+ .success,
+ enabled: !!workspaceId,
+ });
+}
diff --git a/apps/mobile/src/lib/workspace-description.test.ts b/apps/mobile/src/lib/workspace-description.test.ts
new file mode 100644
index 000000000..92d2120a0
--- /dev/null
+++ b/apps/mobile/src/lib/workspace-description.test.ts
@@ -0,0 +1,74 @@
+import { describe, expect, it } from "vite-plus/test";
+
+import {
+ getWorkspaceDescription,
+ workspaceDescriptionUpdate,
+} from "./workspace-description";
+
+describe("workspace descriptions", () => {
+ it("prefers the first-class description over legacy metadata", () => {
+ expect(
+ getWorkspaceDescription({
+ description: "Current description",
+ metadata: { description: "Old description" },
+ }),
+ ).toBe("Current description");
+ });
+
+ it.each([undefined, null, "", " "])(
+ "falls back to legacy object or JSON metadata when the column is %s",
+ (description) => {
+ expect(
+ getWorkspaceDescription({
+ description,
+ metadata: { description: "Legacy description" },
+ }),
+ ).toBe("Legacy description");
+ expect(
+ getWorkspaceDescription({
+ description,
+ metadata: '{"description":"Legacy description"}',
+ }),
+ ).toBe("Legacy description");
+ },
+ );
+
+ it.each([undefined, null, "invalid JSON", "[]", [], 42])(
+ "handles missing or malformed metadata: %j",
+ (metadata) => {
+ expect(getWorkspaceDescription({ metadata })).toBe("");
+ expect(workspaceDescriptionUpdate("New description", metadata)).toEqual({
+ description: "New description",
+ });
+ },
+ );
+
+ it("saves and clears a migrated description without reviving the legacy value", () => {
+ for (const metadata of [
+ {
+ description: "Old description",
+ custom: { enabled: true, value: null },
+ },
+ '{"description":"Old description","custom":{"enabled":true,"value":null}}',
+ ]) {
+ for (const description of ["New description", ""]) {
+ const update = workspaceDescriptionUpdate(description, metadata);
+ expect(update).toEqual({
+ description,
+ metadata: { description, custom: { enabled: true, value: null } },
+ });
+ expect(getWorkspaceDescription(update)).toBe(description);
+ }
+ }
+ });
+
+ it("ignores a non-string legacy description", () => {
+ expect(getWorkspaceDescription({ metadata: { description: 42 } })).toBe("");
+ });
+
+ it("does not rewrite metadata that has no legacy description", () => {
+ expect(
+ workspaceDescriptionUpdate("New description", { custom: "kept" }),
+ ).toEqual({ description: "New description" });
+ });
+});
diff --git a/apps/mobile/src/lib/workspace-description.ts b/apps/mobile/src/lib/workspace-description.ts
new file mode 100644
index 000000000..8505e6790
--- /dev/null
+++ b/apps/mobile/src/lib/workspace-description.ts
@@ -0,0 +1,38 @@
+import type { FullOrganization, Json } from "./api/types";
+
+export function getWorkspaceDescription(
+ workspace: Pick<FullOrganization, "description" | "metadata">,
+): string {
+ if (workspace.description?.trim()) return workspace.description;
+ const metadata = parseMetadata(workspace.metadata);
+ return typeof metadata?.description === "string" ? metadata.description : "";
+}
+
+export function workspaceDescriptionUpdate(
+ description: string,
+ metadata: Json | undefined,
+): { description: string; metadata?: Record<string, Json> } {
+ const parsed = parseMetadata(metadata);
+ // Keep a legacy description in sync, including when clearing the column:
+ // the API falls back to metadata when the column is blank.
+ if (parsed && "description" in parsed) {
+ return { description, metadata: { ...parsed, description } };
+ }
+ return { description };
+}
+
+function parseMetadata(
+ metadata: Json | undefined,
+): Record<string, Json> | undefined {
+ let parsed = metadata;
+ if (typeof parsed === "string") {
+ try {
+ parsed = JSON.parse(parsed) as Json;
+ } catch {
+ return undefined;
+ }
+ }
+ return parsed && typeof parsed === "object" && !Array.isArray(parsed)
+ ? parsed
+ : undefined;
+}
diff --git a/i18n/en-US.json b/i18n/en-US.json
index 295b99fd6..2ac1c28e0 100644
--- a/i18n/en-US.json
+++ b/i18n/en-US.json
@@ -4012,7 +4012,10 @@
"project": "Project",
"create": "Create",
"taskTitle": "Task title",
- "noLabels": "No labels in this workspace yet."
+ "noLabels": "No labels in this workspace yet.",
+ "labelsFailed": "Task created, but some labels couldn't be added.",
+ "parentFailed": "Task created, but it couldn't be linked to the parent. Set the parent from the web app.",
+ "labelsAndParentFailed": "Task created, but some labels and the parent link couldn't be saved."
},
"editor": {
"description": "Description",
@@ -4151,7 +4154,13 @@
"options": "Options",
"separateWithCommas": "Separate with commas",
"androidIOSWeb": "Android, iOS, Web",
- "required": "Required"
+ "required": "Required",
+ "defaultValue": "Default value",
+ "chooseDefault": "Choose a default",
+ "checked": "Checked",
+ "unchecked": "Unchecked",
+ "validDefaultRequired": "Enter a valid default value for this required field.",
+ "multiselectOptionsRequired": "Add at least two different options."
},
"projectNew": {
"newProject": "New project",
@@ -4259,7 +4268,8 @@
"all": "All",
"tasks": "Tasks",
"projects": "Projects",
- "comments": "Comments"
+ "comments": "Comments",
+ "activity": "Activity"
},
"empty": {
"title": "Search this workspace",
diff --git a/i18n/schema.json b/i18n/schema.json
index 93147f4e8..aa81fe1a6 100644
--- a/i18n/schema.json
+++ b/i18n/schema.json
@@ -16293,6 +16293,15 @@
},
"noLabels": {
"type": "string"
+ },
+ "labelsFailed": {
+ "type": "string"
+ },
+ "parentFailed": {
+ "type": "string"
+ },
+ "labelsAndParentFailed": {
+ "type": "string"
}
},
"required": [
@@ -16300,7 +16309,10 @@
"project",
"create",
"taskTitle",
- "noLabels"
+ "noLabels",
+ "labelsFailed",
+ "parentFailed",
+ "labelsAndParentFailed"
]
},
"editor": {
@@ -16829,6 +16841,24 @@
},
"required": {
"type": "string"
+ },
+ "defaultValue": {
+ "type": "string"
+ },
+ "chooseDefault": {
+ "type": "string"
+ },
+ "checked": {
+ "type": "string"
+ },
+ "unchecked": {
+ "type": "string"
+ },
+ "validDefaultRequired": {
+ "type": "string"
+ },
+ "multiselectOptionsRequired": {
+ "type": "string"
}
},
"required": [
@@ -16893,7 +16923,13 @@
"options",
"separateWithCommas",
"androidIOSWeb",
- "required"
+ "required",
+ "defaultValue",
+ "chooseDefault",
+ "checked",
+ "unchecked",
+ "validDefaultRequired",
+ "multiselectOptionsRequired"
]
},
"projectNew": {
@@ -17321,9 +17357,12 @@
},
"comments": {
"type": "string"
+ },
+ "activity": {
+ "type": "string"
}
},
- "required": ["all", "tasks", "projects", "comments"]
+ "required": ["all", "tasks", "projects", "comments", "activity"]
},
"empty": {
"type": "object",