Skip to content

Commit

Permalink
fix: folder count fix when deleting packs
Browse files Browse the repository at this point in the history
  • Loading branch information
farfromrefug committed Oct 22, 2024
1 parent 203beec commit d8983c8
Show file tree
Hide file tree
Showing 4 changed files with 92 additions and 55 deletions.
99 changes: 58 additions & 41 deletions app/components/PacksList.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,16 @@
import { colorTheme, onThemeChanged } from '~/helpers/theme';
import { Pack, PackFolder, RemoteContent, Story } from '~/models/Pack';
import { downloadStories } from '~/services/api';
import { FolderUpdatedEventData, PackAddedEventData, PackDeletedEventData, PackMovedFolderEventData, PackUpdatedEventData, documentsService } from '~/services/documents';
import {
FOLDER_COLOR_SEPARATOR,
FolderUpdatedEventData,
PackAddedEventData,
PackDeletedEventData,
PackMovedFolderEventData,
PackUpdatedEventData,
documentsService,
sql
} from '~/services/documents';
import { BOTTOM_BUTTON_OFFSET, EVENT_FOLDER_UPDATED, EVENT_PACK_ADDED, EVENT_PACK_DELETED, EVENT_PACK_MOVED_FOLDER, EVENT_PACK_UPDATED } from '~/utils/constants';
import {
goToFolderView,
Expand Down Expand Up @@ -52,8 +61,6 @@
import { getRealPath, requestManagePermission } from '~/utils';
const textPaint = new Paint();
const iconPaint = new Paint();
iconPaint.color = '#ffffffcc';
const IMAGE_DECODE_WIDTH = Utils.layout.toDevicePixels(200);
type ViewStyle = 'expanded' | 'condensed' | 'card';
Expand Down Expand Up @@ -91,7 +98,6 @@
colorSurfaceContainerHigh,
colorTertiaryContainer
} = $colors);
iconPaint.fontFamily = mdi;
const screenWidth = Screen.mainScreen.widthDIPs;
export let folder: PackFolder = null;
Expand Down Expand Up @@ -146,7 +152,6 @@
try {
DEV_LOG && console.log('refresh', filter);
const r = await documentsService.packRepository.findPacks({ filter, folder, omitThoseWithFolders: true });
DEV_LOG && console.log('r', r.length);
folders = filter?.length || folder ? [] : await documentsService.folderRepository.findFolders();
Expand Down Expand Up @@ -261,32 +266,31 @@
}
}
}
function onPacksDeleted(event: PackDeletedEventData) {
for (let i = 0; i < event.packIds.length; i++) {
const id = event.packIds[i];
const index = packs.findIndex((item) => item.pack && item.pack.id === id);
if (index !== -1) {
packs.splice(index, 1);
nbSelected -= 1;
async function onPacksDeleted(event: PackDeletedEventData) {
try {
for (let i = 0; i < event.packIds.length; i++) {
const id = event.packIds[i];
const index = packs.findIndex((item) => item.pack && item.pack.id === id);
if (index !== -1) {
packs.splice(index, 1);
nbSelected -= 1;
}
}
}
updateNoPack();
}
function getImageView(index: number) {
const view = collectionView?.nativeView?.getViewForItemAtIndex(index);
return view?.getViewById<Img>('imageView');
}
function onPackPageUpdated(event: EventData & { pageIndex: number; imageUpdated: boolean }) {
// let index = -1;
const pack = event.object as Pack;
const index = packs.findIndex((d) => d.pack.id === pack.id);
if (index >= 0) {
const item = packs?.getItem(index);
if (item) {
item.pack = pack;
packs.setItem(index, item);
if (!folder && event.folders?.length) {
for (let i = 0; i < event.folders.length; i++) {
const name = event.folders[i].split(FOLDER_COLOR_SEPARATOR)[0];
const index = packs.findIndex((item) => item.folder && item.folder.name === name);
if (index !== -1) {
const item = packs.getItem(index);
const res = await documentsService.folderRepository.findFolder(name);
item.folder = res[0];
packs.setItem(index, packs.getItem(index));
}
}
}
updateNoPack();
} catch (error) {
showError(error);
}
}
Expand Down Expand Up @@ -551,7 +555,7 @@
if (currentPack && selectedPacks.findIndex((d) => d.id === currentPack.id)) {
storyHandler?.stopPlaying();
}
await importService.deletePacks(selectedPacks.map((s) => s.id));
await importService.deletePacks(selectedPacks);
}
} catch (error) {
showError(error);
Expand All @@ -571,6 +575,7 @@
vertPos: VerticalPosition.BELOW,
onClose: (item) => {
viewStyle = item.id;
refreshCollectionView();
ApplicationSettings.setString('packs_list_view_style', viewStyle);
}
});
Expand Down Expand Up @@ -621,6 +626,14 @@
return 150;
}
}
function getFolderRowHeight(viewStyle) {
switch (viewStyle) {
case 'card':
return screenWidth / 2;
default:
return 70;
}
}
function getImageMargin(viewStyle) {
switch (viewStyle) {
case 'card':
Expand Down Expand Up @@ -907,9 +920,8 @@
function onFolderCanvasDraw(item: Item, { canvas, object }: { canvas: Canvas; object: CanvasView }) {
const w = canvas.getWidth();
const h = canvas.getHeight();
const dx = 16;
const { folder } = item;
textPaint.fontWeight = 'normal';
// textPaint.color = colorOnSurfaceVariant;
// canvas.drawText(
// filesize(
Expand All @@ -921,32 +933,37 @@
// textPaint
// );
textPaint.color = colorOnBackground;
const cardView = viewStyle === 'card';
const iconSize = cardView ? 70 : 20;
const textSize = cardView ? 22 : 16;
const dx = cardView ? 0 : 16;
const subtitleSize = cardView ? 18 : 14;
const topText = createNativeAttributedString({
spans: [
{
fontFamily: $fonts.mdi,
fontSize: 20 * $fontScale,
fontSize: iconSize * $fontScale,
color: !$folderBackgroundColor && folder.color ? folder.color : colorOutline,
lineHeight: 24 * $fontScale,
text: 'mdi-folder '
lineHeight: iconSize * 1.2 * $fontScale,
text: 'mdi-folder' + (cardView ? '\n' : ' ')
},
{
fontSize: 16 * $fontScale,
fontSize: textSize * $fontScale,
fontWeight: 'bold',
lineBreak: 'end',
lineHeight: 18 * $fontScale,
lineHeight: textSize * 1.2 * $fontScale,
text: folder.name
},
{
fontSize: 14 * $fontScale,
fontSize: subtitleSize * $fontScale,
color: colorOutline,
lineHeight: (condensed ? 14 : 20) * $fontScale,
lineHeight: (condensed ? 14 : subtitleSize * 1.2) * $fontScale,
text: '\n' + lc('packs_count', item.folder.count)
}
]
});
canvas.save();
const staticLayout = new StaticLayout(topText, textPaint, w - dx, LayoutAlignment.ALIGN_NORMAL, 1, 0, true);
const staticLayout = new StaticLayout(topText, textPaint, w - dx, cardView ? LayoutAlignment.ALIGN_CENTER : LayoutAlignment.ALIGN_NORMAL, 1, 0, true);
canvas.translate(dx, 16);
staticLayout.draw(canvas);
canvas.restore();
Expand Down Expand Up @@ -1008,7 +1025,7 @@
borderRadius={12}
borderWidth={1}
fontSize={14 * $fontScale}
height={70 * $fontScale}
height={getFolderRowHeight(viewStyle) * $fontScale}
margin="4 8 4 8"
rippleColor={colorSurface}
on:tap={() => onItemTap(item)}
Expand Down
34 changes: 26 additions & 8 deletions app/services/documents.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ export interface PackUpdatedEventData extends EventData {
}
export interface PackDeletedEventData extends EventData {
packIds: string[];
folders: string[];
}

export interface PackMovedFolderEventData extends EventData {
Expand Down Expand Up @@ -158,10 +159,19 @@ COUNT(pf.pack_id) AS count`,
from: sql`Folder f`,
postfix: sql`
LEFT JOIN PacksFolders pf ON f.id = pf.folder_id
LEFT JOIN Pack p ON pf.pack_id = p.id
GROUP BY f.id;`
});
}
findFolder(name: string) {
return this.search({
select: sql`f.*,
COUNT(pf.pack_id) AS count`,
from: sql`Folder f`,
where: sql`f.name = ${name}`,
postfix: sql`
LEFT JOIN PacksFolders pf ON f.id = pf.folder_id`
});
}
}

export class PackRepository extends BaseRepository<Pack, IPack> {
Expand Down Expand Up @@ -227,8 +237,8 @@ CREATE TABLE IF NOT EXISTS "PacksFolders" (
addSubtitle: sql`ALTER TABLE Pack ADD COLUMN subtitle TEXT`,
addKeywords: sql`ALTER TABLE Pack ADD COLUMN keywords TEXT`,
addType: sql`ALTER TABLE Pack ADD COLUMN type TEXT`,
addExtra: sql`ALTER TABLE Pack ADD COLUMN extra TEXT`
// addColors: sql`ALTER TABLE Pack ADD COLUMN colors TEXT`
addExtra: sql`ALTER TABLE Pack ADD COLUMN extra TEXT`,
cleanGhostFolders: sql`DELETE FROM PacksFolders WHERE pack_id NOT IN (SELECT id FROM Pack)`
});

async createPack(data: Partial<Pack>) {
Expand Down Expand Up @@ -357,11 +367,14 @@ LEFT JOIN
args.where = new SqlQuery([`pf.folder_id = ${folder.id}`]);
}
args.postfix = new SqlQuery((args.postfix ? [args.postfix] : []).concat([foldersPostfix]));
} else if (omitThoseWithFolders) {
args.select = sql`p.*`;
args.from = sql`Pack p`;
args.where = sql`p.id NOT IN(SELECT pack_id FROM PacksFolders)`;
// args.postfix = foldersPostfix;
} else {
if (omitThoseWithFolders) {
args.select = sql`p.*`;
args.from = sql`Pack p`;
args.where = sql`p.id NOT IN(SELECT pack_id FROM PacksFolders)`;
} else {
args.postfix = new SqlQuery((args.postfix ? [args.postfix] : []).concat([foldersPostfix]));
}
}
return this.search(args);
}
Expand Down Expand Up @@ -482,6 +495,11 @@ export class DocumentsService extends Observable {
...(folder ? { folders: [folder] } : {})
});
}

async removePack(id: string) {
await this.packRepository.delete({ id } as any);
await this.db.query(sql` DELETE FROM PacksFolders where pack_id=${id}`);
}
}
export let documentsService: DocumentsService;
export function createSharedDocumentsService() {
Expand Down
3 changes: 2 additions & 1 deletion app/services/importservice.ts
Original file line number Diff line number Diff line change
Expand Up @@ -196,7 +196,8 @@ export class ImportService extends Observable {
this.ensureWorker();
await this.sendMessageToWorker('import_from_file', data, undefined, undefined, false, 0, { db: documentsService.db.db.db });
}
async deletePacks(data: string[]) {
async deletePacks(packs: Pack[]) {
const data = packs.map((s) => ({ id: s.id, folders: s.folders }));
DEV_LOG && console.log('deleteDocuments', JSON.stringify(data));
this.ensureWorker();
await this.sendMessageToWorker('delete_packs', data, undefined, undefined, false, 0, { db: documentsService.db.db.db });
Expand Down
11 changes: 6 additions & 5 deletions app/workers/ImportWorker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -192,18 +192,19 @@ export default class ImportWorker extends Observable {
break;
case 'delete_packs':
await worker.handleStart(event);
const ids = event.data.messageData as string[];
const ids = event.data.messageData as { id: string; folders: string[] }[];
DEV_LOG && console.log('deleteDocuments', ids);
// await this.packRepository.delete(model);
await doInBatch(
await doInBatch<{ id: string; folders: string[] }, void>(
ids,
async (id) => {
await documentsService.packRepository.delete({ id } as any);
async (d) => {
const id = d.id;
await documentsService.removePack(id);
const docData = Folder.fromPath(path.join(documentsService.realDataFolderPath, id));
DEV_LOG && console.log('deleteDocument', docData.path);
await docData.remove();
// we notify on each delete so that UI updates fast
documentsService.notify({ eventName: EVENT_PACK_DELETED, packIds: [id] } as PackDeletedEventData);
documentsService.notify({ eventName: EVENT_PACK_DELETED, packIds: [id], folders: d.folders } as PackDeletedEventData);
},
1
);
Expand Down

0 comments on commit d8983c8

Please sign in to comment.